我刚刚开始使用F#,并为我编写的一些功能编写了一些单元测试。为了简洁起见,我决定创建一些不同测试用例的列表,并在一个测试中运行它们,而不是为每个测试创建单独的测试方法(我在这里不关注这个设计决策,只是指出,否则我的问题就没有什么意义了)。
这是我的密码:
// simple helper to cut down on repeated code
let testRunner cases func =
cases |> List.map func
// isNumeric is the function under test, its functionality should be obvious
[<Test>]
let ``IsNumericTest``() =
let testCases = ["123"; "Foo"; "123Foo123"]
let expectedResults = [true; false; false]
let results = testRunner testCases isNumeric
results |> should equal expectedResults我开始考虑创建一个简单的类型来封装测试用例输入和预期的结果,如下所示:
type TestCase = { Input : string; ExpectedResult : bool}
type TestCases = TestCase list
let testCases = [{Input="123"; ExpectedResult=true};{Input="Foo"; ExpectedResult=false}; {Input="123Foo123"; ExpectedResult=false}]然后,我很难想出如何在我的testRunner方法中将其中的每一个拆分出来,直到我想出了这样的方法:
let results = testRunner (testCases |> List.map (fun (T) -> T.Input)) isNumeric
results |> should equal (testCases |> List.map (fun (T) -> T.ExpectedResult))但那看起来很难看。是否有更好的方法来拆分我的Input方法的testRunner值?我可以改变它,但我认为,虽然我的问题是特定于一个单元测试场景,我应该吸取的教训将广泛适用。
发布于 2015-02-10 07:29:04
既然你在NUnit上,为什么不直接使用它的内置测试用例属性呢?然后,您的测试将如下所示:
[<TestCase("123", true)>]
[<TestCase("Foo", false)>]
[<TestCase("123Foo123", false)>]
let ``IsNumericTest``(candidate : string, expected : bool) =
let actual = isNumeric candidate
actual |> should equal expectedxUnit.net (一个更好的.NET单元测试框架)具有类似的特性。
https://codereview.stackexchange.com/questions/80106
复制相似问题