我有@BeforeClass
设置,我为测试套件运行运行,如下所示:
@RunWith(Categories.class)
@IncludeCategory(IntegrationTest.class)
.
.
.
public class IntegrationTestSuite {
@BeforeClass
public static void initialise() throws Exception {
// Integration test-specific config.
}
}
当我通过套件运行所有测试时,这很有效。但是,当我运行单个测试时,显然这些东西不会被执行。有没有更优雅的方法可以让我在测试用例级别重用测试类别设置?
考虑创建一个自定义规则(可能利用 ExternalResourse),该规则将仅执行一次初始化。使用一个测试对其他测试进行初始化的机制是一种反模式。它太脆弱了,因为它取决于测试的运行顺序,并且在仅运行单个测试时也会失败。我认为@Rule
机制是一个更好的解决方案。
我建议使用全局标志作为静态上下文或在属性文件中作为:
public static boolean runTestCaseStandAlone = false;
或
boolean runTestCaseStandAlone = properties.get("run.test.case.alone");
将测试套件方法更新为:
public class IntegrationTestSuite {
@BeforeClass
public static void initialise() throws Exception {
if(!GLOBALCONTEXT.runTestCaseStandAlone){
// Integration test-specific config.
}
}
}
为您的测试用例创建一个基类,例如
public class BaseTest ....
@BeforeClass
public static void initialise() throws Exception {
if(GLOBALCONTEXT.runTestCaseStandAlone){
// Integration test-specific config.
}
}
确保所有单独的测试用例都扩展了上述基类。