TestNG Framework Questions [ 2024 ]
TestNG Framework Questions
This post will review some of the TestNG framework questions asked in testing interviews. Test your TestNG knowledge by taking the quiz:
How to you test for an exception in TestNG?
@Test(expectedExceptions = {ArithmeticException.class}) public void divideWithZeroWithException() { int i = 9/0; }
How do you specify the timeout for tests in TestNG?
We can configure timeouts in the suite file or for each test in @Test annotation.
package com.testingdocs.testng.sample; import org.testng.annotations.Test; public class TimeOutExample { @Test(timeOut = 10000) public void timeTakingTestSimulation() throws InterruptedException { Thread.sleep(60000); System.out.println("Print testcase pass after 1 minute"); } }
In the above, example we have specified the test to take about 60 sec.
Furthermore, we have specified timeout as 10 sec in the annotation.
So, if the method doesn’t complete under 10 sec it will be marked as a failure.
Output:
FAILED: timeTakingTestSimulation
org.testng.internal.thread.ThreadTimeoutException: Method org.testng.internal.TestNGMethod.timeTakingTestSimulation() didn’t finish within the time-out 10000
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
How do you ignore or disable a test in TestNG?
We can disable a test in TestNG using the attribute “enabled=false” with the @Test annotation.
@Test(enabled=false) public void ignoreThisTest() { System.out.println(" TestingDocs.com >>> Ignore this test .. Anyways this wont run "); }
Write sample code snippet for method dependency?
package com.testingdocs.testng.sample; import org.testng.Assert; import org.testng.annotations.Test; public class MethodDependency { @Test() public void methodOne(){ System.out.println("This method will execute first"); Assert.assertEquals("ABC", "ABC"); } @Test(dependsOnMethods={"methodOne"}) public void dependentMethod(){ System.out.println("This is dependent method, this method will be skipped if methodOne fails"); Assert.assertEquals("ABC", "ABC"); } }
PASSED: methodOne
PASSED: dependentMethod
===============================================
Default test
Tests run: 2, Failures: 0, Skips: 0
===============================================
We will make the first method as a failure and check the output.
FAILED: methodOne
java.lang.AssertionError: expected [ABCD] but found [ABC]
SKIPPED: dependentMethod
java.lang.Throwable: Method MethodDependency.dependentMethod()
===============================================
Default test
Tests run: 2, Failures: 1, Skips: 1
===============================================
In conclusion, practice a lot of tests in IDE to master the TestNG framework. Also, try to practice writing suite files for different test combinations.