简体   繁体   English

Junit Test Case构造函数调用参数化的运行程序

[英]Junit Test Case constructor calls in parameterized runner

I wrote a long parameterized test, one of whose parameters is a constructor call with double-brace syntax to construct a different object for each row of the 2D array: 我编写了一个长参数化测试,其中一个参数是一个带有双括号语法的构造函数调用,为2D数组的每一行构造一个不同的对象:

Object[][] data = new Object[][] {
{ 1, 2, 3, new Blah() {{ setA(); }} }
{ 1, 2, 3, new Blah() {{ setB(); }} }
...

Since the philosophy of JUnit is to call the test case constructor on each @Test, I was assuming that it would do the same with parameterized tests - but I'm seeing that it's only calling that constructor (the constructor defined for the parameterized test) once per row, not once per test per row. 由于JUnit的原理是在每个@Test上调用测试用例构造函数,我假设它会对参数化测试做同样的事情 - 但我发现它只调用那个构造函数(为参数化测试定义的构造函数)每行一次,每行测试一次。

So, the test fields are behaving globally and tests are affecting each other. 因此,测试字段表现为全局,测试相互影响。 I want to know if there's a way to force the runner to call the constructor for each tests, as with the regular JUnit runner. 我想知道是否有一种方法可以强制运行器为每个测试调用构造函数,就像使用常规JUnit运行器一样。 Google and the JUnit pages are not helping me on this case. 在这种情况下,Google和JUnit页面并没有帮助我。 I'd really rather not rewrite the entire test, which is extensive and fairly readable at this point. 我真的不想重写整个测试,这个广泛且相当可读。

I'm not sure if I completely follow you but when the test is run, this is what happens: 我不确定我是否完全跟随你,但是当测试运行时,会发生以下情况:

  1. The method you've annotated with @Parameters method is called once and only once. 使用@Parameters方法注释的方法只调用一次。
  2. A test runner instance is created for each row in the collection returned by the annotated method. 为带注释的方法返回的集合中的每一行创建一个测试运行器实例。
  3. The test is instantiated for each row in the parameter collection using its constructor, but it is passed in the corresponding parameter value row that was cached from the initial invocation. 测试实例使用它的构造函数参数采集中的每一行,但它是从最初的调用缓存中相应的参数值行通过。

You can see where this happens by clicking here and here . 您可以点击此处此处查看这种情况。 If you're mutating state between calls (using a static method or whatever) expect to see weird things. 如果你在调用之间改变状态(使用静态方法或其他什么),期望看到奇怪的事情。

Edit: After poking around in the code, I understand better what you're asking now. 编辑:在代码中探讨之后,我会更好地理解你现在所要​​求的内容。 I've just debugged a parameterized test using JUnit 4.10 and it does indeed invoke the constructor once per row per test. 我刚刚使用JUnit 4.10调试了一个参数化测试,它确实每次测试每行调用一次构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM