The JUnit 4's runner API also has an important deterrent. As described in chapter 1, Retrospective on software quality and Java testing, in JUnit 4 a runner is a Java class used to manage a test's life cycle. The runner API in JUnit 4 is quite powerful, nevertheless, it has an important drawback: runners are not composable, that is, we can only use a single runner at a time.
For example, a parameterized test cannot be combined with the Spring test support, due to the fact that both tests would use their own runner implementation. Thinking in Java (see the snippets given follow), each test case uses its own unique @RunWith annotation. The first one uses the Parameterized runner:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class MyParameterizedTest {
@Test
public void myFirstTest() {
// my test code
}
}
While this second example is using the SpringJUnit4ClassRunner runner, it would not be combined with the previous one due to a limitation on JUnit 4 (runners are not composable):
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
public class MySpringTest {
@Test
public void yetAnotherTest() {
// my test code
}
}