QA Interview: Top 40: TestNG Interview Questions for QA (21:40)

 Other Useful Links:



21. How to handle exceptions in TestNG?
  • If we expect errors from some methods, we can include the exception in the @Test annotation so that the test case does not fail.
  • Example: If a method is intended to throw the "numberFormatException" exception, the test case will fail since there is no try-catch block given. However, using the "expectedException" feature in TestNG, we can accomplish this.
        @Test(expectedException=numberFormatException.class)
        The test case will then execute successfully.

22. How to disable a test in TestNG?

 In TestNG, we must utilize the "enabled" attribute as follows to disable a test:
 @Test(enabled=”false”)

23. How to skip a @Test method from execution in TestNG?
  • By using throw new SkipException()
  • When SkipException() is issued, the remaining test method code is not executed, and control is passed to the next test method.
  • throw new SkipException("Skip");

24. What are the common TestNG assertions?

(i) Assert.assetEquals(String actual, String expected)
  • It accepts two strings.
  • The test case executes successfully if both strings are equal; else, the test case fails.
(ii) Assert.assertEquals(String actual, String expected, String message)
  • It accepts two strings.
  • The test case succeeds if both strings are equal, otherwise it fails.
  • If a test case fails, a message is printed.
(iii) Assert.assertEquals(boolean actual, boolean expected)
  • It accepts two boolean values.
  • The test case executes successfully if both boolean values are equal; else, the test case fails.
(iv) Assert.assertTrue(<condition(t/f)>)
  • It accepts a boolean value.
  • If the condition is True, the assertion succeeds; otherwise, an assertion error is displayed.
(v) Assert.assertFalse(<condition(t/f)>)
  • It accepts a boolean value.
  • If the condition is True, the assertion succeeds; otherwise, an assertion error is displayed.
(vi) Assert.assertTrue(<condition(t/f)>,message)
  • It accepts a boolean value.
  • If the condition is True, the assertion succeeds; otherwise, an assertion error with the message is displayed.
(vii) Assert.assertFalse(<condition(t/f)>,message)
  • It accepts a boolean value.
  • If the condition is False, the assertion succeeds; otherwise, an assertion error with the message is displayed.

25. What are the types of Asserts in TestNG?

(i) Hard Assert:
Hard Assert is the standard assert used in the TestNG class to perform validations.
Assert.assertEquals(actual value, expected value);
If the hard assert fails, none of the code after the assert line is run.

(ii) Soft Assert:
Soft assert must be used if we want the test to continue running even if the assert statement fails.
softAssert sassert = new softAssert();
sassert.assertAll();
When we use soft assert, the execution is not terminated if the test case fails.

26. What is the difference between soft assertion and hard assertion?

Soft Assertion: In the case of Soft Assertion, if an assertion fails during @Test, TestNG will throw an exception and proceed to the next statement after the assert statement.

Hard Assertion: In the case of Hard Assertion, if an assertion fails during @Test, TestNG will instantly issue an AssertException and stop execution after the assert statement.

27. What are listeners in TestNG?
  • Listeners are a type of code in TestNG that listens for specific events and then executes the code associated with that event.
  • As a result, we can adjust TestNG's default behavior using TestNG listeners. Furthermore, in TestNG, the tester has access to a large number of listeners with various features.

28. How are listeners declared in TestNG?

The TestNG listener code is kept separate from the TestNG test case file. Following that, this file contains the listener code, and the type of listener to use is determined by "implementing" the listener class as follows:

public class ListenersTestNG implements ITestListener {
public void onStart(ITestContext context) {
System.out.println("onStart method started");
}
}

We declare the @Listener annotation and provide the listener class name in the following way to inform the TestNG test case file about the listener:

@Listeners(ListenersTestNG.class)
public class TestNG {
WebDriver driver = new FirefoxDriver();
@Test  //Success Test
public void CloseBrowser() {
driver.close();
}
}

29. What are the requirements for creating a customised report in TestNG? 
  • With the help of TestNG listeners, a customized report is generated.
  • We may control events like method start, method pass, fail, and so on using the TestNG interface ITestListener, and a tester can report relevant messages based on these occurrences.

30. Can you put the testng.xml tags in the correct order from parent to child?

The TestNG tags should be in the following order:
<suite>
<test>
<classes>
<class>
<methods>

31. How to exclude a particular test method from a test case execution? 
By adding the exclude tag in the testng.xml:
<classes>
  <class name="TestCaseName">
     <methods>
       <exclude name="TestMethodNameToExclude"/>
     </methods>
  </class>      
</classes>

32. What is the importance of testng.xml file?
  • It specifies the order in which all test cases are executed.
  • It allows you to arrange test cases and execute them according to the specifications.
  • It executes the selected test cases.
  • Listeners can be implemented at the suite level in TestNG.
  • It enables you to use the TestNG framework with other tools like Jenkins.

33. In data-driven testing, which characteristic is utilized to supply data to the test method?

In data-driven testing, the dataProvider attribute is used to provide data directly to the test function.
Syntax: @Test(dataProvider = "getData")

34. What is the return type of DataProvider?
  • array of object (Object [ ][ ])

35. What is the difference between @BeforeTest and @BeforeMethod annotation?

@BeforeTest is executed once before each of the testng <test> tag mentioned in the testng.xml file 
@BeforeMethod is executed before each and every test script method.

36. How to re-execute failed test cases using TestNG?


Run testng-failed.xml

  • After the first run of an automated test run, right click on the project and then click on refresh.
  • A folder will be created named ‘test-output’
  • Inside the test output folder you will find testng-failed.xml.
  • Run testng-failed.xml to execute failed test cases

IRetryAnalyzer

To implement IRetryAnalyzer, create a class called RetryFailedTestCases.


Import org.testng.IRetryAnalyzer;

Import org.testng.ITestResult;

public class RetryFailedTestCases implements IRetryAnalyzer{

private int retrycount=0;

private int maxretrycount=0;


public boolean retry(ITestResult result){

if(retrycount<maxretrycount){

System.out.println(“Retrying:”+result.getName());

retrycount++;

return true;

}

return false;

}

}


Import org.testng.IRetryAnalyzer;

Import org.testng.IAnnotationTransformer;

Import org.testng.annotations.*;

public class RetryListnerClass implements IAnnotationTransformer{

@override

public void transform(ITestAnnotation testannotation,Class testclass, Constructor testconstructor, Method testmethod){

IRetryAnalyzer retry = testannotation.getRetryAnalyzer();

if(retry == null){

testannotation.setRetryAnalyzer(RetryFailedTestCases.class);

}

}

}


TestNG.xml:

<listners>

<listner class-name=”packagename.RetryListnerClass”/>

<listners>


37. How do you use TestNG to run several test cases in parallel?

In TestNG, the "parallel" feature can be used to achieve parallel test execution. The parallel attribute of the suite tag has four options:
  1. tests: Test cases inside <test> tag of testng.xml file will run parallel
  2. classes:  Test cases inside a java class will run parallel
  3. methods: Methods marked with the @Test annotation will run in parallel.
  4. instances: In the same instance, test cases will run on parallel, but two methods from two different instances will run in separate threads.
<suite name="CreditCardTest" parallel="methods">

38. Running Test Methods Parallely in TestNG


import org.openqa.selenium.*;

import org.testng.annotations.*;

public class ParallelTestDemo{

public WebDriver driver;

@Test

public void FirefoxTest(){

driver = new FireFoxDriver();

driver.get(“http://www.demo.com”);

driver.findElement(By.id(“Button”)).click();

driver.close();

}

@Test

public void ChromeTest(){

driver = new ChromeDriver();

driver.get(“http://www.demo.com”);

driver.findElement(By.id(“Button”)).click();

driver.close();

}

}


TestNG.xml:

<suite name=”Parallel testing suite”>

<test name=”parallel tests” parallel=”methods”>

<classes>

<class name=”ParallelTestDemo”/>

</classes>

</test>

</suite>


39. What is thread-count in TestNG?
  • If parallel mode is enabled, the thread-count attribute in TestNG is utilised to run the maximum number of threads for each suite (otherwise ignore it).
  • Thread-count = "2" for example: Your tests will be executed in two threads.

40. How can we use TestNG to pass a parameter to the test script?

We can pass parameters to test scripts using the @Parameter annotation and the 'parameter' tag in testng.xml.
Sample testng.xml:

<suite name="sampleTestSuite">
   <test name="sampleTest">   
      <parameter name="sampleParamName" value="sampleParamValue"/>
      <classes>
         <class name="TestFile" />
      </classes>      
   </test>
</suite>

Greetings, reader! Your input is highly important to us. Please share your thoughts in the comments section below.


Contact:

Email:  piyushagrawal.automation@gmail.com

Follow on LinkedIn: Piyush Agrawal - LinkedIn

Follow on YouTube: Piyush Agrawal - Youtube

Happy to Help You !!

No comments:

Post a Comment