首页 > 解决方案 > 如何根据之前的@Test测试结果在TestNG中启用@Test方法

问题描述

我在下面的类及其@Test 方法中有一个条件:

class myClass{

    @Test
    public void test1(){..}

    @Test
    public void test2(){..}

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

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

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

标签: testng

解决方案


可以通过 boolean 变量进行设置并抛出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);
        }
    }
}

推荐阅读