Passing discriminated unions to InlineData attributes

爷,独闯天下 提交于 2019-12-10 17:37:16

问题


I am trying to unit test a parser that parses a string and returns the corresponding abstract syntax tree (represented as a discriminated union). I figured it would be pretty compact to use Xunit.Extensions' attribute InlineData to stack all test cases on one another:

[<Theory>]
[<InlineData("1 +1 ", Binary(Literal(Number(1.0)), Add, Literal(Number(1.0))))>]
...
let ``parsed string matches the expected result`` () =

However, compiler complains that the second argument is not a literal (compile time constant if I understand it correctly).

Is there a workaround for this? If not, what would be the most sensible way to structure parser result tests while keeping every case as a separate unit test?


回答1:


One possibility is to use xUnit's MemberData attribute. A disadvantage with this approach is that this parameterized test appears in Visual Studio's Test Explorer as one test instead of two separate tests because collections lack xUnit's IXunitSerializable interface and xUnit hasn't added build-in serialization support for that type either. See xunit/xunit/issues/429 for more information.

Here is a minimal working example.

module TestModule

  open Xunit

  type DU = A | B | C

  type TestType () =
    static member TestProperty
      with get() : obj[] list =
        [
          [| A; "a" |]
          [| B; "b" |]
        ]

    [<Theory>]
    [<MemberData("TestProperty")>]            
    member __.TestMethod (a:DU) (b:string) =
      Assert.Equal(A, a)

See also this similar question in which I give a similar answer.



来源:https://stackoverflow.com/questions/27726058/passing-discriminated-unions-to-inlinedata-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!