JUnit @Parameterized function is run before @BeforeClass in a test suite?
Recently ran into similar issue and solved problem using Function. Example below.
@RunWith(Parameterized.class)
public class MyClassTest {
@Parameterized.Parameters
public static Iterable functions() {
return Arrays.<Object, Object>asList(
param -> new Object()
);
}
Object param;
Function function;
public MyClassTest(Function f) {
this.function = f;
}
@Before
public void before() {
// construct dependency
param = "some value";
}
@Test
public void test() {
assertThat(myClass.doSomething(function.apply(param)), is(equalTo(expectedValue)));
}
}
In your scenario, do database setup in @Before or @BeforeClass then inject into function
This is, unfortunately, working as intended. JUnit needs to enumerate all of the test cases before starting the test, and for parameterized tests, the method annotated with @Parameterized.Parameters
is used to determine how many tests there are.
Although beeing a bit different solution, a static block does the trick. Also note, that it must be in the Test1.class. But beside of that it works ;-)
@RunWith(Parameterized.class)
public class Test1 {
static{
System.out.println("Executed before everything");
}
private String value;
// @Parameterized function which appears to run before @BeforeClass setup()
@Parameterized.Parameters
public static Collection<Object[]> configurations() throws InterruptedException {
// Code which relies on setup() to be run first
}
public Test1(String value) {
this.value = value;
}
@Test
public void testA() {
// Test
}
}