Search code examples
javaspringjunitspring-test

How to run JUnit SpringJUnit4ClassRunner with Parametrized?


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?


Solution

  • There are at least 2 options to do that:

    1. 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:

       @RunWith(Parameterized.class)
       @ContextConfiguration(classes = {ApplicationConfigTest.class})
       public class ServiceTest {
      
           private TestContextManager testContextManager;
      
           @Before
           public void setUpContext() throws Exception {
               //this is where the magic happens, we actually do "by hand" what the spring runner would do for us,
              // read the JavaDoc for the class bellow to know exactly what it does, the method names are quite accurate though
             this.testContextManager = new TestContextManager(getClass());
             this.testContextManager.prepareTestInstance(this);
           }
           ...
       }
      
    2. There is a github project https://github.com/mmichaelis/spring-aware-rule, which builds on previous blog, but adds support in a generalized way

      @SuppressWarnings("InstanceMethodNamingConvention")
      @ContextConfiguration(classes = {ServiceTest.class})
      public class SpringAwareTest {
      
          @ClassRule
          public static final SpringAware SPRING_AWARE = SpringAware.forClass(SpringAwareTest.class);
      
          @Rule
          public TestRule springAwareMethod = SPRING_AWARE.forInstance(this);
      
          @Rule
          public TestName testName = new TestName();
      
          ...
      }
      

    So you can have a basic class implementing one of the approaches, and all tests inheriting from it.