The following code is invalid due to duplicate @RunWith
annotation:
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(Parameterized.class)
@SpringApplicationConfiguration(classes = {ApplicationConfigTest.class})
public class ServiceTest {
}
But how can I use these two annotations in conjunction?
There are at least 2 options to do that:
Following http://www.blog.project13.pl/index.php/coding/1077/runwith-junit4-with-both-springjunit4classrunner-and-parameterized/
Your test needs to look something like this:
There is a github project https://github.com/mmichaelis/spring-aware-rule, which builds on previous blog, but adds support in a generalized way
So you can have a basic class implementing one of the approaches, and all tests inheriting from it.
You can use SpringClassRule and SpringMethodRule - supplied with Spring
There is another solution with JUnit 4.12 without the need of Spring 4.2+.
JUnit 4.12 introduces ParametersRunnerFactory which allow to combine parameterized test and Spring injection.
The factory can be added to test class to give full Spring support like test transaction, reinit dirty context and servlet test.
If you need Spring context inside @Parameters static method to provide parameters to test instances, please see my answer here How can I use the Parameterized JUnit test runner with a field that's injected using Spring?.
Handle application context by yourself
What worked for me was having a
@RunWith(Parameterized.class)
test class that managed the application context "by hand".To do that I created an application context with the same string collection that would be in the
@ContextConfiguration
. So instead of havingI had
And for each @Autowired I needed I fetched it by hand from the created context:
Do not forget to close the context at the end: