如何使用参数化运行JUnitSPringJUnit4ClassRunner?

2022-08-31 14:46:33

由于重复的注释,以下代码无效:@RunWith

@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(Parameterized.class)
@SpringApplicationConfiguration(classes = {ApplicationConfigTest.class})
public class ServiceTest {
}

但是,如何结合使用这两个注释呢?


答案 1

您可以使用SpringClassRule和SpringMethodRule - 与Spring一起提供

import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;

@RunWith(Parameterized.class)
@ContextConfiguration(...)
public class MyTest {

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    ...

答案 2

至少有2个选项可以做到这一点:

  1. 后续 http://www.blog.project13.pl/index.php/coding/1077/runwith-junit4-with-both-springjunit4classrunner-and-parameterized/

    您的测试需要如下所示:

     @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. 有一个github项目 https://github.com/mmichaelis/spring-aware-rule,它建立在以前的博客上,但以一种通用的方式添加了支持。

    @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();
    
        ...
    }
    

因此,您可以有一个实现其中一种方法的基本类,以及从中继承的所有测试。


推荐