DEV Community

Kuldeep Rana
Kuldeep Rana

Posted on

TestNG Interview Questions for Experienced Professionals

Hello friends! TestNG is one of the most common testing frameworks used in the automated testing suites. In this article, I am sharing 5 of the top testNG interview questions.

Ques. How can we skip a testNG test case conditionally?
Ans. TestNG provides an exception by the name - SkipException. We can throw this exception inside our conditional statement like this-
@Test
public void testMethod(){
if(conditionToCheckForSkippingTest)
throw new SkipException("Skipping the test");
//test logic
}

Ques. How can we pass parameter to our test script?
Ans. This can be achieved with the help of @Parameter annotation and ‘parameter’ tag in the testng.xml.

<parameter name="sampleParamName" value="sampleParamValue"/>

Sample test script-
public class Test {
@Test
@Parameters("sampleParam")
public void parameterTest(String paramValue) {
System.out.println("Value of sampleParam is - " + sampleParam);
}

Ques. How can we run our test cases in parallel?
Ans. In order to run the tests in parallel just add these two key-value pairs-


parallel="{methods/tests/classes}"
thread-count="{number of thread}".

Ques. What is the use of @Listener annotation?
Ans. TestNG provides us different kinds of listeners using which we can perform some action in case an event gets triggered. We can use these listeners for various purposes like - taking screenshots in case of failure, logging, etc.

@Listeners(PackageName.CustomizedListenerClassName.class)

public class TestClass {
WebDriver driver= new FirefoxDriver();@test
public void testMethod(){
//test logic
}
}

Ques. What is the use of @Factory annotation?
Ans. The @Factory annotation helps in the dynamic execution of the testNG tests. Using @Factory annotation, we can pass parameters to the whole test class at run time.
public class TestClass{
private String str;
public TestClass(String str) {
this.str = str;
}

@Test
public void TestMethod() {
    System.out.println(str);
}

}

public class TestFactory{
//The test methods in class TestClass will run twice with data "k1" and "k2"
@Factory
public Object[] factoryMethod() {
return new Object[] { new TestClass("K1"), new TestClass("k2") };
}
}

To learn more about the different capabilities of a TestNG, refer to this comprehensive TestNG Tutorial.

Top comments (0)