【问题标题】:In @SpringBootTest, is there a way to have SpringRunner.class and Theories.class co-exist?在@SpringBootTest 中,有没有办法让 SpringRunner.class 和 Theories.class 共存?
【发布时间】:2019-11-14 16:37:43
【问题描述】:
希望这是一个简单的问题。
我有一个 Spring Boot 测试。
注释是:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@TestPropertySource(locations { "myproperties.properties" })
我有一个我很想使用@RunWith(Theories.class) 的测试。该测试在我的代码中的几个不同位置测试基本相同的东西。
当然,@RunWith 必须是单数。
那么有没有办法让这些理论开始成为一项规则?还是 SpringRunner.class?或者是什么让它们可以共存?
【问题讨论】:
标签:
spring-boot-test
springrunner
【解决方案1】:
应该有两种方法来解决这个问题:
-
SpringClassRule 和 SpringMethodRule
随便用
@RunWith(Theories.class)
public class YourTest {
@ClassRule
public static final SpringClassRule scr = new SpringClassRule();
@Rule
public final SpringMethodRule smr = new SpringMethodRule()
-
手动初始化 TestContextManager 根据 Baeldung 它适用于 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);
}