在测试之间传递 JUnit 数据
我刚刚发现在创建一些 CRUD 测试时,您无法在一个测试中设置数据并在另一个测试中读取数据(数据在每个测试之间设置回其初始化状态)。
我想做的就是通过一个测试 (C) 创建一个对象,并通过下一个测试 (R) 读取它。 JUnit 是否有办法做到这一点,或者它的编码思想不允许测试相互依赖?
I just discovered when creating some CRUD tests that you can't set data in one test and have it read in another test (data is set back to its initialization between each test).
All I'm trying to do is (C)reate an object with one test, and (R)ead it with the next. Does JUnit have a way to do this, or is it ideologically coded such that tests are not allowed to depend on each other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
那么,对于单元测试,您的目标应该是测试最小的独立代码段,通常是逐个方法。
所以
testCreate()
是一个测试用例,testRead()
是另一个测试用例。但是,没有什么可以阻止您创建testCreateAndRead()
来一起测试这两个函数。但是如果测试失败,测试会在哪个代码单元失败呢?你不知道。这类测试更像是集成测试,应该区别对待。如果您确实想这样做,可以创建一个静态类变量来存储
testCreate()
创建的对象,然后在testRead()
中使用它。由于我不知道你所说的 Junit 版本是什么,所以我只是选择了古老的 Junit 3.8:
极其丑陋但有效:
Well, for unit tests your aim should be to test the smallest isolated piece of code, usually method by method.
So
testCreate()
is a test case andtestRead()
is another. However, there is nothing that stops you from creating atestCreateAndRead()
to test the two functions together. But then if the test fails, which code unit does the test fail at? You don't know. Those kind of tests are more like integration test, which should be treated differently.If you really want to do it, you can create a static class variable to store the object created by
testCreate()
, then use it intestRead()
.As I have no idea what version of Junit you talking about, I just pick up the ancient one Junit 3.8:
Utterly ugly but works:
JUnit 提倡独立测试。一种选择是将两个逻辑测试放入一个 @Test 方法中。
TestNG 的创建部分是为了允许测试之间存在此类依赖关系。它强制执行测试依赖项的本地声明——它以有效的顺序运行测试,并且不运行依赖于失败测试的测试。请参阅http://testng.org/doc/documentation-main.html#dependent-方法 为例。
JUnit promotes independent tests. One option would be to put the two logical tests into one @Test method.
TestNG was partly created to allow these kinds of dependencies among tests. It enforces local declarations of test dependencies -- it runs tests in a valid order, and does not run tests that depend on a failed test. See http://testng.org/doc/documentation-main.html#dependent-methods for examples.
JUnit 是独立测试。但是,如果你没有办法,你可以使用“静态”实例来存储它。
JUnit is independent test. But, If you have no ways, you can use "static" instance to store it.
这些测试需要多少处理时间?如果不是很多,那为什么要流汗呢?当然,您会创建一些不必要的对象,但这会花费您多少钱?
How much processing time do these tests take? If not a lot, then why sweat it. Sure you will create some object unnecessarily, but how much does this cost you?
在这个基本示例中,变量在测试 A 中更改,并且可以在测试 B 中使用
输出结果为:
run A
run B
shareVar is: blah
in this basic example, the variable is changed in the test A, and can be used in the test B
output result is:
run A
run B
sharedVar is: blah