如何根据之前的@Test测试结果在TestNG中启用@Test方法

How to enable @Test method in TestNG based on previous @Test test results

我这里有一个条件,如下所示 class 及其 @Test 方法:

class myClass{

    @Test
    public void test1(){..}

    @Test
    public void test2(){..}

    @Test
    public void test3(enabled=false){..}
}

这里我想在上面的@Tests(test1 or test2)中的任何一个失败时执行@Test test3。

问题,测试结果,我的意思是结果(通过或失败)。不是他们返回的值。

这里需要使用dependsOnMethods。所以,当测试1和测试2都通过后,才会执行测试3。
您可以像这样使用它:

@Test(dependsOnMethods={"test1", "test2"})
public void test3{...}

如果你想 运行 第三个测试用例,当前两个失败时,你可以在 beforeMethod 中抛出 SkipException 当你不希望测试用例 运行.
你可以取一个全局的布尔值,然后根据你的测试用例pass/fail条件设置。

boolean condition = true;

// Execute before each test is run
@BeforeMethod
public void before(Method methodName){
    // check condition, note once you condition is met the rest of the tests will be skipped as well
    if(condition){
        throw new SkipException();
    }
}

可以通过布尔变量并抛出 SkipException 这将中断所有后续测试的执行:

class myClass{
    // skip variable
    boolean skipCondition;

    // Execute before each test is run
    @BeforeMethod
    public void before(Method methodName){
        // condition befor execute
        if(skipCondition)
            throw new SkipException();
    }

    @Test(priority = 1)
    public void test1(){..}

    @Test(priority = 2)
    public void test2(){..}

    @Test(priority = 3)
    public void test3(){..}
}

另一个正在实施 IAnnotationTransformer,比较复杂。

public class ConditionalTransformer implements IAnnotationTransformer {
    // calls before EVERY test
    public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod){
        // add skip ckeck
        if (skipCkeck){
            annotation.setEnabled(false);
        }
    }
}