I am using a JUnit test suite to run a few tests, one of which is run multiple times using @Parameterized. I am finding that when I run my tests, the @Parameterized function is run before @BeforeClass. Is this expected behavior or is something else happening? I would have expected that @BeforeClass would run before any of the tests are started.
Here is my test suite:
@RunWith(Suite.class)
@SuiteClasses({ Test1.class, Test2.class })
public class TestSuite {
@BeforeClass
public static void setup() throws Exception {
// setup, I want this to be run before anything else
}
}
Test1 uses @Parameterized:
public class Test1 {
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
}
}
How can I fix this to run the @BeforeClass setup() function before running anything else?
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
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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With