我有一个项目,在每个@Test方法之前,我都要检查该方法的注释数据是否有效。如果数据无效,我想跳过测试方法并继续其余的测试套件。
所有数据解析和逻辑工作正常,但据我所知我使用的工具不正确。
我的代码有...
private SoftAssert s_assert = new SoftAssert();
@BeforeMethod
public void beforeMethod(Method m){
//reads code
if (dataNotCorrect)
s_assert.fail();
}
@Test @MyCustomAnnotation(data = incorrect)
public void Test1(){
//Do stuff
}
@Test @MyCustomAnnotation(data = correct)
public void Test2(){
//Do stuff
}
在这种情况下,我想开始尝试同时执行这两种操作,但是当测试运行时,应跳过Test1(),而Test2()应该正常运行。然而,一旦我发现失败,它将立即结束整个套件。
我已经尝试了使用软断言和普通断言,但似乎都没有用。
SkipException是您要寻找的。
在beforeMethod
中,检查您的数据,如果它们不正确,则抛出SkipException
。这将跳过测试。在此完整而简单的示例中,跳过了test2
:
import org.testng.SkipException;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
public class TestA {
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
boolean dataCorrect();
}
@BeforeMethod
public void beforeMethod(Method m) {
if (!m.getAnnotation(MyCustomAnnotation.class).dataCorrect()) {
throw new SkipException("Invalid data");
}
}
@Test
@MyCustomAnnotation(dataCorrect = true)
public void test1() {
System.out.println("test1");
}
@Test
@MyCustomAnnotation(dataCorrect = false)
public void test2() {
System.out.println("test2");
}
}
另请参见:How do I use TestNG SkipException?
您还需要更改默认的配置失败策略,即使跳过一个测试,也可以运行其他测试。这是在套件级别完成的:
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" configfailurepolicy="continue">
...
</suite>
感谢OP指向@Kyle指向此属性。
@@ Benoit使我在大多数情况下都可以通过抛出SkipException来代替断言。但是我仍然希望跳过当前测试而不是其余所有测试的问题仍然存在。
问题出在Testng中的configfailurepolicy。当我希望将其设置为继续(继续套件的其余部分)时,它默认跳过(跳过所有剩余测试)。
这里是我在其他地方找到的答案,我设法以两种不同的方式来应用。 Link here
1。首先,创建一个testng.xml并从那里运行测试。在套件名称旁边,添加标签configfailurepolicy =“ continue”这是我下面的testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" configfailurepolicy="continue">
<test name="MyTests" preserve-order="true">
<classes>
<class name="testclassLocation..." />
</classes>
</test>
</suite>
如果这样做,请确保从testng.xml运行测试。
2。找到用于testng的.jar所在的位置。我正在使用Maven,因此它是“ $ {user.dir} .m2 \ repository \ org \ testng \ testng \ 6.14.3”。
然后打开.jar存档,查看文件'testng-1.0.dtd',找到该行
configfailurepolicy (skip | continue) "skip"
并将其更改为
configfailurepolicy (skip | continue) "continue"
此后应该可以正常工作。
编辑:如评论中所述,建议使用第一种解决方案,因为它可以使这些更改/修复在多个项目/设备之间移植。第二种解决方案将仅将修复程序应用于您的计算机。
在BeforeMethod中创建一个静态布尔标志,如果数据不正确,则将标志更改为true,然后在布尔测试为true时,先将标志设置为false并通过测试失败
样本代码
public static Boolean myflag=false;
@BeforeMethod
public void beforeMethod(Method m){
//reads code
if (dataNotCorrect)
myflag=true;
}
@Test @MyCustomAnnotation(data = incorrect)
public void Test1(){
if(myflag){
myflag=false;
s_assert.fail();
}