F#可以使用哪些单元测试框架

Gre*_*egC 14 f# unit-testing fsunit f#-unquote

我正在寻找能够利用该语言的独特功能的框架.我知道FsUnit.你会推荐别的吗?为什么?

Ste*_*sen 26

我自己的单元测试库Unquote利用F#引用,允许您将测试断言编写为普通的,静态检查的F#布尔表达式,并自动生成很好的逐步测试失败消息.例如,以下失败的xUnit测试

[<Fact>]
let ``demo Unquote xUnit support`` () =
    test <@ ([3; 2; 1; 0] |> List.map ((+) 1)) = [1 + 3..1 + 0] @>
Run Code Online (Sandbox Code Playgroud)

产生以下失败消息

Test 'Module.demo Unquote xUnit support' failed: 

([3; 2; 1; 0] |> List.map ((+) 1)) = [1 + 3..1 + 0]
[4; 3; 2; 1] = [4..1]
[4; 3; 2; 1] = []
false

        C:\File.fs(28,0): at Module.demo Unquote xUnit support()
Run Code Online (Sandbox Code Playgroud)

FsUnit和Unquote有类似的任务:允许您以惯用的方式编写测试,并生成信息性的失败消息.但是FsUnit实际上只是NUnit Constraints的一个小包装器,创建了一个隐藏可组合函数调用背后的对象构造的DSL.但它需要付出代价:在断言中丢失静态类型检查.例如,以下内容在FsUnit中有效

[<Test>]
let test1 () =
    1 |> should not (equal "2")
Run Code Online (Sandbox Code Playgroud)

但是使用Unquote,你可以获得所有F#的静态类型检查功能,因此等效的断言甚至不能编译,从而阻止我们在测试代码中引入错误

[<Test>] //yes, Unquote supports both xUnit and NUnit automatically
let test2 () =
    test <@ 1 <> "2" @> //simple assertions may be written more concisely, e.g. 1 <>! "2"
    //           ^^^
    //Error 22 This expression was expected to have type int but here has type string
Run Code Online (Sandbox Code Playgroud)

此外,由于引用能够在编译时捕获有关断言表达式的更多信息,因此失败消息也更丰富.例如,失败的FsUnit断言1 |> should not (equal 1)产生消息

Test 'Test.Swensen.Unquote.VerifyNunitSupport.test1' failed: 
  Expected: not 1
  But was:  1
    C:\Users\Stephen\Documents\Visual Studio 2010\Projects\Unquote\VerifyNunitSupport\FsUnit.fs(11,0): at FsUnit.should[a,a](FSharpFunc`2 f, a x, Object y)
    C:\Users\Stephen\Documents\Visual Studio 2010\Projects\Unquote\VerifyNunitSupport\VerifyNunitSupport.fs(29,0): at Test.Swensen.Unquote.VerifyNunitSupport.test1()
Run Code Online (Sandbox Code Playgroud)

失败的Unquote断言1 <>! 1产生以下失败消息(注意更清洁的堆栈跟踪)

Test 'Test.Swensen.Unquote.VerifyNunitSupport.test1' failed: 

1 <> 1
false

    C:\Users\Stephen\Documents\Visual Studio 2010\Projects\Unquote\VerifyNunitSupport\VerifyNunitSupport.fs(29,0): at Test.Swensen.Unquote.VerifyNunitSupport.test1()
Run Code Online (Sandbox Code Playgroud)

当然,从我在本答案开头的第一个例子中,您可以看到Unquote表达式和失败消息的丰富性和复杂性.

使用普通F#表达式作为FsUnit DSL上的测试断言的另一个主要好处是它非常适合开发单元测试的F#过程.我认为很多F#开发人员都是在FSI的帮助下开发和测试代码的.因此,从ad-hoc FSI测试到正式测试非常容易.实际上,除了对xUnit和NUnit的特殊支持之外(尽管也支持任何基于异常的单元测试框架),所有Unquote运算符也在FSI会话中工作.

  • 我试过Unquote,因为这里有所有的赞成票,一周之后我卖掉了.到目前为止,我发现有价值:在fsi中编写测试,然后将它们移动到NUnit; 与NUnit的集成; 测试表达式的强类型(Unquote发现了一个只有偶然传递的测试); 引用实用程序,例如"eval".如果您有Nuget,则可以使用"install-package Unquote"安装Unquote. (3认同)