1

希望这是一个简单的问题。

我有一个 Spring Boot 测试。

注释是:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@TestPropertySource(locations { "myproperties.properties" })

我有一个我很想使用@RunWith(Theories.class) 的测试。该测试在我的代码中的几个不同位置测试基本相同的东西。

当然,@RunWith 必须是单数。

那么有没有办法让这些理论开始成为一项规则呢?还是 SpringRunner.class?或者是什么让它们可以共存?

4

1 回答 1

0

应该有两种方法来解决这个问题:

  1. SpringClassRule 和 SpringMethodRule <-- 我使用这种方法

    只需使用

    @RunWith(Theories.class)
    public class YourTest {
        @ClassRule
        public static final SpringClassRule scr = new SpringClassRule();
    
        @Rule
        public final SpringMethodRule smr = new SpringMethodRule()
    
  2. 根据Baeldung手动初始化 TestContextManager它适用于Parameterized,但我不知道为什么它也不适用于Theories ;) 通常,不建议手动初始化 TestContextManager。相反,Spring 建议使用 SpringClassRule 和 SpringMethodRule。

    @RunWith(Parameterized.class)
    public class YourTest {
    
        private TestContextManager testContextManager;
        @Before
        public void setup() throws Exception {
            this.testContextManager = new TestContextManager(getClass());
            this.testContextManager.prepareTestInstance(this);
        }
    
于 2020-05-07T06:24:36.517 回答