首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >构造测试数据

构造测试数据
EN

Code Review用户
提问于 2015-02-10 01:55:21
回答 1查看 58关注 0票数 2

我刚刚开始使用F#,并为我编写的一些功能编写了一些单元测试。为了简洁起见,我决定创建一些不同测试用例的列表,并在一个测试中运行它们,而不是为每个测试创建单独的测试方法(我在这里不关注这个设计决策,只是指出,否则我的问题就没有什么意义了)。

这是我的密码:

代码语言:javascript
复制
// 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

我开始考虑创建一个简单的类型来封装测试用例输入和预期的结果,如下所示:

代码语言:javascript
复制
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方法中将其中的每一个拆分出来,直到我想出了这样的方法:

代码语言:javascript
复制
let results = testRunner (testCases |> List.map (fun (T) -> T.Input)) isNumeric
results |> should equal (testCases |> List.map (fun (T) -> T.ExpectedResult))

但那看起来很难看。是否有更好的方法来拆分我的Input方法的testRunner值?我可以改变它,但我认为,虽然我的问题是特定于一个单元测试场景,我应该吸取的教训将广泛适用。

EN

回答 1

Code Review用户

回答已采纳

发布于 2015-02-10 07:29:04

既然你在NUnit上,为什么不直接使用它的内置测试用例属性呢?然后,您的测试将如下所示:

代码语言:javascript
复制
[<TestCase("123", true)>]
[<TestCase("Foo", false)>]
[<TestCase("123Foo123", false)>]
let ``IsNumericTest``(candidate : string, expected : bool) =
    let actual = isNumeric candidate
    actual |> should equal expected

xUnit.net (一个更好的.NET单元测试框架)具有类似的特性。

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/80106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档