gpt4 book ai didi

unit-testing - 哪些单元测试框架可用于 F#

转载 作者:行者123 更新时间:2023-12-03 21:16:04 25 4
gpt4 key购买 nike

我正在专门寻找允许我利用该语言独特功能的框架。我知道 FsUnit .你会推荐其他东西吗,为什么?

最佳答案

我自己的单元测试库,Unquote ,利用 F# quotations允许您将测试断言编写为简单的、静态检查的 F# bool 表达式,并自动生成漂亮的分步测试失败消息。例如,以下失败的 xUnit 测试

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

产生以下失败消息
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()

FsUnit 和 Unquote 有类似的任务:允许您以惯用的方式编写测试,并生成信息丰富的失败消息。但 FsUnit 实际上只是 NUnit 约束的一个小包装,创建了一个 DSL,它将对象构造隐藏在可组合函数调用之后。但这是有代价的:你在断言中丢失了静态类型检查。例如,以下在 FsUnit 中有效
[<Test>]
let test1 () =
1 |> should not (equal "2")

但是使用 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

此外,由于引用能够在编译时捕获有关断言表达式的更多信息,因此失败消息也更加丰富。例如失败的 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()

而失败的 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()

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

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

关于unit-testing - 哪些单元测试框架可用于 F#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5667372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com