How to run JUnit SpringJUnit4ClassRunner with Parametrized?

后端 未结 4 1242
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 16:16

The following code is invalid due to duplicate @RunWith annotation:

@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(Parameterized.class)
@Sprin         


        
4条回答
  •  渐次进展
    2020-12-12 16:46

    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.

    public class SpringParametersRunnerFactory implements ParametersRunnerFactory {
    @Override
      public Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
        final BlockJUnit4ClassRunnerWithParameters runnerWithParameters = new BlockJUnit4ClassRunnerWithParameters(test);
        return new SpringJUnit4ClassRunner(test.getTestClass().getJavaClass()) {
          @Override
          protected Object createTest() throws Exception {
            final Object testInstance = runnerWithParameters.createTest();
            getTestContextManager().prepareTestInstance(testInstance);
            return testInstance;
          }
        };
      }
    }
    

    The factory can be added to test class to give full Spring support like test transaction, reinit dirty context and servlet test.

    @UseParametersRunnerFactory(SpringParametersRunnerFactory.class)
    @RunWith(Parameterized.class)
    @ContextConfiguration(locations = {"/test-context.xml", "/mvc-context.xml"})
    @WebAppConfiguration
    @Transactional
    @TransactionConfiguration
    public class MyTransactionalTest {
    
      @Autowired
      private WebApplicationContext context;
    
      ...
    }
    

    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?.

提交回复
热议问题