How to use Return in TestNG Methods
We have in Java that a method can return some value after processing the data, so here we are going to learn a method that can return value or not in a testNG class.
Sample Code:
package TestAnnotation; import org.testng.annotations.Test; public class ValueReturningTest { // A @Test method which is returning a value will be ignored by TestNG @Test public String returnMethod() { System.out.println(“Returning Method”); return “SOftwareTestingo”; } @Test public void normalMethod() { System.out.println(“Normal Method”); } }
When we execute the above testng class, in the output you can see in tests, run showing one whereas we have two methods. That means if we are using the return statement inside a testNG method, then that method is skipped by testNG.
Similarly, we are going to learn another new thing which is, can we call another test method from a test method?
In response to the above question, we can say that we can call a test method from another test method.
package TestAnnotation; import org.testng.annotations.Test; public class ValueReturningTest { // A @Test method which is returning a value will be ignored by TestNG @Test public String returnMethod() { System.out.println("Returning Method"); return "SOftwareTestingo"; } @Test public void normalMethod() { System.out.println("Normal Method"); System.out.println(returnMethod()); } }
As we all know that, TestNG is mainly used for unit testing, and a unit test method should not return a value. Thats why when a method returns some value that method is ignored by the testNG which is the default behaviour of TestNG.
But we can force TestNG to add those methods in the execution which are returning values by mentioning allow-return-values as true at the suite level.
Here is the testng.xml file with updated:
<?xml version="1.0" encoding="UTF-8"?> <suite name="Suite" allow-return-values="true"> <test thread-count="5" name="Test"> <classes> <class name="TestAnnotation.ValueReturningTest" /> </classes> </test> <!-- Test --> </suite> <!-- Suite -->
Note: We can force to TestNG to change the behaviour, but the return value is not displaying in the result.
Where can we use this concept?
TestNG is a testing framework which can be used by both developers and testers. This concept can be used when you need to inherit an interface or abstract class and test its methods without changing method signatures.
Source: link
Leave a Reply