Bala
Bala

Reputation: 204

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

I have a condition here like in below class and its @Test methods:

class myClass{

    @Test
    public void test1(){..}

    @Test
    public void test2(){..}

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

Here I want to execute the @Test test3 when either of the above @Tests(test1 or test2) gets failed.

In question, test results, what I exactly mean is result (Pass or Fail). Not the value they returned.

Upvotes: 2

Views: 843

Answers (2)

Eugen
Eugen

Reputation: 917

It is posible to make through boolean variable and throwing SkipException this will brake out all subsequent tests execution:

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(){..}
}

The onother one is implementing IAnnotationTransformer, more complicated.

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);
        }
    }
}

Upvotes: 1

Sameer Arora
Sameer Arora

Reputation: 4507

You need to use dependsOnMethods here. So, when both the Test 1 and Test 2 pass, only then Test 3 will be executed.
You can use it like:

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

If you want to run the third test case when either of first two fails then you can throw SkipException in beforeMethod when you don't want the test case to run.
You can take a global boolean value and then set it according to your test case pass/fail condition.

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();
    }
}

Upvotes: 2

Related Questions