[英]Can I Skip Junit Tests if other tests fail?
我正在使用Junit通过Seleniun WebDriver运行测试。 我试图将测试分成功能区域,以更好地报告错误。 我创建了测试以测试页面加载/将文档移动到其他工作流程。 如果页面加载测试失败,或者工作流移动失败,我想跳过后续的页面/工作流测试。
如果测试A失败,如何跳过该类中的其余测试或在B类中运行测试?
注意:我意识到我要问的是“ UNIT TESTS的不良实践*。但是,实际上我正在使用Junit进行集成和/或自动化测试。(取决于您的定义。)我已经找到@Suite.SuiteClasses
和@FixMethodOrder
来排序我的测试类和测试方法,我试图让它们逻辑上运行,首先测试页面加载,然后再测试页面的每个功能作为单独的测试。其中一些功能会移动信息到其他页面,也就是其他班级。我的班级之一可能需要超过1/2小时才能完成。如果先决条件测试失败,我想将“从属”测试短路,以得到我的结果/尽快报告。
我建议您切换到TestNG。 检查这个出来。
顺便说一句:大约一年以前,当我曾经使用Java时,我没有为JUnit找到这样的解决方案。
您可以尝试通过“规则”界面操作测试,这里有一个示例: http : //www.codeaffine.com/2013/11/18/a-junit-rule-to-conditionally-ignore-tests/
那可能是一个很好的起点。
通过在@Before或@Test方法中使用Junit的Assume ,可以使用以下任一方法跳过当前测试
这是一个例子:
public class Tests{
@Test
public void test1(){
...
}
@Test
public void test2(){
try{
test1();
}catch(AssertionError failExcep){
//test1 failed, skip this test
Assume.assumeTrue(false);
}catch(AssumptionVoilationException skipExcep){
//test1 was skipped, skip this test
Assume.assumeNoException(skipExcep);
}
...
}
}
这个特定的示例将运行两次test1(),但是要添加@FixMethodOrder并捕获在test1期间抛出的任何错误,以在test2中进行引用; 我们可以规避这个问题。
另外,此示例也没有涵盖test1()可能引发的任何其他异常类型,例如NullPointerException。 将AssumptionVoilationException catch子句编辑为Exception将允许在发生任何异常时跳过test2。 如果您还想捕获Error或Throwable,只需添加一个catch子句并放入Assume.assumeTrue(false)即可,如AssertionError。 或者你可以抛出AssumptionViolatedException
这是虚拟证明版本
@FixMethodOrder
public class Tests{
private Optional<Throwable> testOneThrown;
@Test
public void test1(){
try{
...
}catch(Throwable t){
// test1 throw something, catching it for test2() reference
testOneThrown = Optional.of(t);
/*
* still throwing it for junit normal functions and
* in case test2 ran independently
*/
throw t;
}
//Ran successfully, making reference non-null but empty
testOneThrown = Optional.empty();
}
@Test
public void test2(){
try{
if(testOneThrown == null){
// test1 did not run, thus needs to run
test1();
}else if(testOneThrown.isPresent()){
// test1 ran and threw something
throw testOneThrown.get();
}
//test1 ran and throw nothing
}catch(Throwable thrown){
/*
* something was throw in test1, test1 could have
* failed, could have been skipped, etc. thus skip
* this test.
*/
throw new AssumptionViolatedException("Dependency on test1 failed.", thrown);
}
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.