JUnit-@RunWith: SpringJUnit4ClassRunner vs. Parameterized
If you like Spring but you also like data-driven-testing (DDT) you will soon run into a problem: both approaches require to define a runner with @RunWith – but JUnit only allows one runner for one test class.
A blog post by Konrad ‘ktoso’ Malawski actually points to a very interesting approach which is to copy the test-initialization behavior of the SpringJUnit4ClassRunner: @RunWith JUnit4 with BOTH SpringJUnit4ClassRunner and Parameterized.
- before test class
- before test method
- after test method
- after test class
To solve these issues you can extend calls to the TestContextManager to @BeforeClass, @AfterClass and @After. But to have a reusable pattern we placed the solution into a JUnit Rule. Because it needs to run in test class and test method mode there is a slight quirk: You have to use the rule as @ClassRule as well as @Rule.
Usage in test:
@ClassRule public static final SpringAware SPRING_AWARE = SpringAware.forClass(SpringAwareTest.class); @Rule public TestRule springAwareMethod = SPRING_AWARE.forInstance(this);
Having this you can configure your test nearly just as if you have a SpringJUnit4Runner (with ContextConfiguration and such) despite some exceptions. The following annotations are not interpreted:
There might be more differences – just as always with any copy & paste approach.
Find the rule and a small example test as GitHub Repository.