什么是“正确的”? 如何测试Java方法的输出?
在 Python 中,我经常进行如下所示的测试:
tests = [
(2, 4),
(3, 9),
(10, 100),
]
for (input, expected_output) in tests:
assert f(input) == expected_output
在 Java 中使用 JUnit 编写这样的测试(指定一组测试用例,然后循环运行每个测试用例)的“正确”方法是什么?
谢谢!
先发制人的响应:我意识到我可以做类似的事情:
assertEquals(4, f(2))
assertEquals(9, f(3))
....
但是......我希望有更好的方法。
In Python, I often have tests which look something like this:
tests = [
(2, 4),
(3, 9),
(10, 100),
]
for (input, expected_output) in tests:
assert f(input) == expected_output
What is the "right" way to write tests like this (where a set of test cases is specified, then a loop runs each of them) in Java with JUnit?
Thanks!
Preemptive response: I realize I could do something like:
assertEquals(4, f(2))
assertEquals(9, f(3))
....
But... I'm hoping there is a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
一样。
当然不如 python 漂亮,但很少有东西是这样的。
您可能还想研究 JUnit 理论,这是一个未来的功能......
Same thing.
Certainly not as pretty as python but few things are.
You may also want to look into JUnit Theories, a future feature...
正确的方法是编写单独的断言语句,即使您不喜欢它。
它避免了不必要的复杂化,并且当失败时,有时更容易看出哪个值失败了(无需启动调试器)。
但是,如果您自动生成测试数据,那就是另一回事了。
The right way is writing separate assert statements, even if you don't like it.
It avoids unnecessary complications, and when it fails it is sometimes easier to see which value failed (no need to start up the debugger).
However, if you generate your test data automatically it is a different story.
查看 Junit 中的参数化测试运行器。
http://junit.org/apidocs/org/junit/runners/Parameterized。 html
看起来它会精确地执行您正在寻找的操作。
Have a look at the Parameterized test runner in Junit.
http://junit.org/apidocs/org/junit/runners/Parameterized.html
It looks like it will do precisely what you are looking for.
嗯...
同样的事情,真的。 唯一的问题是 Java 缺乏元组文字,因此对于更复杂的情况,您必须使用 Object[] 数组并进行强制转换,或者编写一个 Tuple 类。
Um...
Same thing, really. The only problem is Java's lack of a tuple literal, so for more complex cases, you'll have to use Object[] arrays and cast, or write a Tuple class.
您是否只定义一个包含两个字段(实际结果和预期结果)的简单类,然后以与 Python 代码片段类似的方式循环遍历集合?
Wouldn't you just define a simple class with two fields, real result and expected result and then loop over the collection in a similar way to what your Python snippet is doing?
Java 中没有元组,但您可以使用 Map 或两个并行数组来指定输入/输出对,然后像 Python 示例一样执行循环。
There are no tuples in Java, but you could use a Map or two parallel arrays to specify input/output pairs and then do a loop just like your Python example.
绝对不是单元测试方面的专家,但我更愿意为我正在测试的每种情况使用单独的方法,并使用一些测试运行工具(例如用于 C# 的 NUnit-GUI)。 这样我就能准确地知道哪个案例失败了(如果失败的话)。 虽然还有更多工作要做,但我认为最终会得到很好的回报。
Definitely not an expert on unit testing but i would prefer to have a separate method for each case that I am testing against and use some test running tools (like NUnit-GUI, for C#). That way I would exactly know which case fails, if it does. Its more work to do, but i think it eventually pays off well.