How to Skip execution of test case based on output value of particular method or variable

30 views
Skip to first unread message

lakshmi prasanna

unread,
Apr 16, 2024, 1:53:50 AMApr 16
to testng-users
I have 10 test cases  where as 5/10 test cases are based on the one particular value. If my variable  has value then my test case should execute or else they should skip.

currently i am using if else condition inside the test case.
is there any other alternative

Krishnan Mahadevan

unread,
Apr 16, 2024, 10:54:07 AMApr 16
to testng...@googlegroups.com
Here’s one easy way of doing it.

You create a base class that implements the IHookable interface and within this interface implementation, you add your condition and if the condition fails, you merely throw a SkipException.

Here’s a complete sample

Base class looks like this

import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.SkipException;

import java.util.Optional;

public class TestBase implements IHookable {
    @Override
    public void run(IHookCallBack callBack, ITestResult testResult) {
        Object[] parameters = Optional.ofNullable(testResult.getParameters()).orElse(new Object[0]);
        if (parameters.length == 0) {
            callBack.runTestMethod(testResult);
            return;
        }
        boolean flag = Boolean.parseBoolean(parameters[0].toString());
        if (flag) {
            callBack.runTestMethod(testResult);
        } else {
            throw new SkipException("Skipping test " + testResult.getMethod().getMethodName());
        }
    }
}

The test class looks like this

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class MyTestClass extends TestBase {

    @Test(dataProvider = "data")
    public void test(boolean flag) {
        System.err.println("Hello World");
    }

    @DataProvider
    public Object[][] data() {
        return new Object[][]{
                {true},
                {false}
        };
    }
}



Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"
My Scribblings @ http://wakened-cognition.blogspot.com/
My Technical Scribblings @ https://rationaleemotions.com/

--
You received this message because you are subscribed to the Google Groups "testng-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to testng-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/testng-users/849a054b-b904-43e2-8651-681a5fbb6bben%40googlegroups.com.

Reply all
Reply to author
Forward
0 new messages