将已区分的并集传递给InlineData属性 [英] Passing discriminated unions to InlineData attributes

查看:165
本文介绍了将已区分的并集传递给InlineData属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对解析字符串的语法分析器进行单元测试,并返回相应的抽象语法树(表示为有区别的并集).我认为使用Xunit.Extensions的属性InlineData可以将所有测试用例相互堆叠会很紧凑:

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?

推荐答案

一种可能性是使用xUnit的MemberData属性.这种方法的一个缺点是,此参数化测试在Visual Studio的测试资源管理器"中显示为一个测试,而不是两个单独的测试,因为集合缺少xUnit的IXunitSerializable接口,并且xUnit也没有为该类型添加内置的序列化支持.有关更多信息,请参见 xunit/xunit/issues/429 .

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.

这篇关于将已区分的并集传递给InlineData属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆