Question

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:

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.

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. Google and the JUnit pages are not helping me on this case. I'd really rather not rewrite the entire test, which is extensive and fairly readable at this point.

Was it helpful?

Solution

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.
  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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top