TestNG – Plug with Eclipse

TestNG – Plug with Eclipse ”; Previous Next To set up TestNG with Eclipse, follow the steps given below − Step 1: Download TestNG Archive Download the latest version of TestNG jar file from http://www.testng.org OS Archive name Windows testng-7.4.jar Linux testng-7.4.jar Mac testng-7.4.jar We assume you have copied the above JAR file in /work/testng folder. Step 2: Set Eclipse environment Open eclipse → right click on the project and go to property → Build Path → Configure Build Path and add the testng-7.4.jar in the libraries using Add External Jar button. We assume that your Eclipse has inbuilt TestNG plug-in; if it is not available, then please get the latest version using the update site. In your Eclipse IDE, select Help / Eclipse Marketplace. Search for Testng. You will get the TestNG in the list. Click on Install as shown below: Now, your Eclipse is ready for the development of TestNG test cases. Step 3: Verify TestNG Installation in Eclipse Create a project TestNGProject in Eclipse at any location. Create a class MessageUtil to test in the project. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } } Create a test class TestNGExample in the project. import org.testng.Assert; import org.testng.annotations.Test; public class TestNGExample { String message = “Hello World”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { Assert.assertEquals(message,messageUtil.printMessage()); } } The project structure should be as follows − Finally, verify the output of the program by right-clicking on the program and running as TestNG. Verify the result. Print Page Previous Next Advertisements ”;

TestNG – Parameterized Test

TestNG – Parameterized Test ”; Previous Next Another interesting feature available in TestNG is parametric testing. In most cases, you”ll come across a scenario where the business logic requires a hugely varying number of tests. Parameterized tests allow developers to run the same test over and over again using different values. TestNG lets you pass parameters directly to your test methods in two different ways − With testng.xml With Data Providers Passing Parameters with testng.xml With this technique, you define the simple parameters in the testng.xml file and then reference those parameters in the source files. Let us have an example to demonstrate how to use this technique to pass parameters. Create Test Case Class Create a java test class, say, ParameterizedTest1.java. Add test method parameterTest() to your test class. This method takes a string as input parameter. Add the annotation @Parameters(“myName”) to this method. The parameter would be passed a value from testng.xml, which we will see in the next step. Create a java class file named ParameterizedTest1.java in /work/testng/src. import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class ParameterizedTest1 { @Test @Parameters(“myName”) public void parameterTest(String myName) { System.out.println(“Parameterized value is : ” + myName); } } Create testng.xml Create testng.xml in /work/testng/src to execute test case(s). <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <parameter name = “myName” value=”manisha”/> <classes> <class name = “ParameterizedTest1″ /> </classes> </test> </suite> We can also define the parameters at the <suite> level. Suppose we have defined myName at both <suite> and <test> levels. In such cases, regular scoping rules apply. It means that any class inside <test> tag will see the value of parameter defined in <test>, while the classes in the rest of the testng.xml file will see the value defined in <suite>. Compile the test case class using javac. /work/testng/src$ javac ParameterizedTest1.java Now, run testng.xml, which will run the parameterTest method. TestNG will try to find a parameter named myName first in the <test> tag, and then, if it can’t find it, it searches in the <suit> tag that encloses it. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Parameterized value is : manisha =============================================== Suite1 Total tests run: 1, Failures: 0, Skips: 0 =============================================== TestNG will automatically try to convert the value specified in testng.xml to the type of your parameter. Here are the types supported − String int/Integer boolean/Boolean byte/Byte char/Character double/Double float/Float long/Long short/Short Passing Parameters with Dataproviders When you need to pass complex parameters or parameters that need to be created from Java (complex objects, objects read from a property file or a database, etc.), parameters can be passed using Dataproviders. A Data Provider is a method annotated with @DataProvider. This annotation has only one string attribute: its name. If the name is not supplied, the data provider’s name automatically defaults to the method’s name. A data provider returns an array of objects. The following examples demonstrate how to use data providers. The first example is about @DataProvider using Vector, String, or Integer as parameter, and the second example is about @DataProvider using object as parameter. Example 1 Here, the @DataProvider passes Integer and Boolean as parameter. Create Java class Create a java class called PrimeNumberChecker.java. This class checks if the number is prime. Create this class in /work/testng/src. public class PrimeNumberChecker { public Boolean validate(final Integer primeNumber) { for (int i = 2; i < (primeNumber / 2); i++) { if (primeNumber % i == 0) { return false; } } return true; } } Create Test Case Class Create a java test class, say, ParamTestWithDataProvider1.java in /work/testng/src. Define the method primeNumbers(), which is defined as a Data provider using the annotation. This method returns an array of objects. Add the test method testPrimeNumberChecker() to your test class. This method takes an Integer and Boolean as input parameters. This method validates if the parameter passed is a prime number. Add the annotation @Test(dataProvider = “test1”) to this method. The attribute dataProvider is mapped to “test1”. Following are the contents of ParamTestWithDataProvider1.java. import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ParamTestWithDataProvider1 { private PrimeNumberChecker primeNumberChecker; @BeforeMethod public void initialize() { primeNumberChecker = new PrimeNumberChecker(); } @DataProvider(name = “test1”) public static Object[][] primeNumbers() { return new Object[][] {{2, true}, {6, false}, {19, true}, {22, false}, {23, true}}; } // This test will run 4 times since we have 5 parameters defined @Test(dataProvider = “test1″) public void testPrimeNumberChecker(Integer inputNumber, Boolean expectedResult) { System.out.println(inputNumber + ” ” + expectedResult); Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber)); } } Create testng.xml Create a testng.xml /work/testng/src to execute Test case(s). <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <classes> <class name = “ParamTestWithDataProvider1″ /> </classes> </test> </suite> Compile the Test case class using javac. /work/testng/src$ javac ParamTestWithDataProvider1.java PrimeNumberChecker.java Now, run testng.xml. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. 2 true 6 false 19 true 22 false 23 true =============================================== Suite1 Total tests run: 5, Failures: 0, Skips: 0 =============================================== Example 2 Here, the @DataProvider passes Object as parameter. Create Java class Create a java class Bean.java, which is a simple object with get/set methods, in /work/testng/src. public class Bean { private String val; private int i; public Bean(String val, int i) { this.val = val; this.i = i; } public String getVal() { return val; } public void setVal(String val) { this.val = val; } public int getI() { return i; } public void setI(int i) { this.i = i; } } Create Test Case Class Create a java test class, say, ParamTestWithDataProvider2.java. Define the method primeNumbers(), which is defined as a data provider using annotation. This method returns an array of object. Add the test method testMethod() to your test class. This method takes an object bean as parameter. Add the annotation @Test(dataProvider = “test1”) to this method. The attribute dataProvider is mapped to “test1”. Create a java class file named ParamTestWithDataProvider2.java in /work/testng/src. import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public

TestNG – Test Results

TestNG – Test Results ”; Previous Next Reporting is the most important part of any test execution, as it helps the user understand the result of the test execution, point of failure, and the reasons for failure. Logging, on the other hand, is important to keep an eye on the execution flow or for debugging in case of any failures. TestNG, by default, generates a different type of report for its test execution. This includes an HTML and an XML report output. TestNG also allows its users to write their own reporter and use it with TestNG. There is also an option to write your own loggers, which are notified at runtime by TestNG. There are two ways to generate a report with TestNG − Listeners − For implementing a listener class, the class has to implement the org.testng.ITestListener interface. These classes are notified at runtime by TestNG when the test starts, finishes, fails, skips, or passes. Reporters − For implementing a reporting class, the class has to implement an org.testng.IReporter interface. These classes are called when the whole suite run ends. The object containing the information of the whole test run is passed to this class when called. In this chapter, we will have four different examples to demonstrate four different cases of reporting and logging − Sr.No. Case & Example 1 Custom Logging This example illustrates how to write your own logger. 2 Custom Reporter This example illustrates how to write your own reporter. 3 HTML and XML report This example illustrates the default HTML and XML report generated by TestNG. 4 JUnit Reports This example illustrates how to generate JUnit reports from TestNG reports. Print Page Previous Next Advertisements ”;

TestNG – Annotation Transformers

TestNG – Basic Annotations – Transformers ”; Previous Next In some scenarios you might want to execute TestNG tests based on some condition or criteria that is evaluated dynamically while test execution is in progress.Such as : Enable or disable a test Add data provider at run time In order to achieve this, you need to use an Annotation Transformer. An Annotation Transformer is a class that implements the following interface: public interface IAnnotationTransformer { /** * This method will be invoked by TestNG to give you a chance * to modify a TestNG annotation read from your test classes. * You can change the values you need by calling any of the * setters on the ITest interface. * * Note that only one of the three parameters testClass, * testConstructor and testMethod will be non-null. * * @param annotation The annotation that was read from your * test class. * @param testClass If the annotation was found on a class, this * parameter represents this class (null otherwise). * @param testConstructor If the annotation was found on a constructor, * this parameter represents this constructor (null otherwise). * @param testMethod If the annotation was found on a method, * this parameter represents this method (null otherwise). */ public void transform(ITest annotation, Class testClass, Constructor testConstructor, Method testMethod); } You can specify this class either on the command line or with ant as shown below: java org.testng.TestNG -listener TestTransformer testng.xml or programmatically as shown below: TestNG test = new TestNG(); test.setAnnotationTransformer(new TestTransformer()); // … This interface IAnnotationTransformer modifies the default TestNG tests behavior at run time. Using this listener, we can modify values of all attributes defined in @Test annotation by calling their setters. Create a Class Let”s see the usage of annotation transformer in below example. Let us skip tests that are tagged to a specified group without changing TestNG suite every time. Create a java class to be tested, say, ListenerTest.java in /work/testng/src. import org.testng.annotations.Test; public class ListenerTest { @Test(groups={“betaTest”,”aplhaTest”}) public void test1() { System.out.println(“I am test1”); } @Test(groups={“aplhaTest”}) public void test2() { System.out.println(“I am test2″); } } Create Tansformer class Case Class Create a java test class, say, TestTransformer.java(that implements IAnnotationTransformer) in /work/testng/src. Override method transform(). Add an Annotation @Test to methods test1() and test2() and group them. Add logic to skip tests with group name betaTest. Following are the TestTransformer.java contents. import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public class TestTransformer implements IAnnotationTransformer{ @Override public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { List groupNames = Arrays.asList(annotation.getGroups()); System.out.println(groupNames.toString()); //Value ”betaTest” can be read from many places like properties file, run time parameter etc… //For Simplicity, group is hardcoded in this program String groupNameToSkip = “betaTest”; if(groupNames.contains(groupNameToSkip)){ System.out.println(“found group name”); annotation.setEnabled(false); } } } Create testng.xml Next, let”s create testng.xml file in /work/testng/src, to execute test case(s). <suite name=”Suite” parallel=”classes” thread-count=”2″> <listeners> <listener class-name=”TestTransformer”></listener> </listeners> <test name=”Test”> <classes> <class name=”ListenerTest”/> </classes> </test> </suite> Compile the test case using javac. /work/testng/src$ javac TestTransformer.java ListenerTest.java Now, run the testng.xml, which will run the test case defined in <test> tag. As you can see the tests grouped under name betaTest are skipped. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. [aplhaTest] [betaTest, aplhaTest] found group name I am test2 =============================================== Suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;

TestNG – Basic Annotations

TestNG – Basic Annotations ”; Previous Next The traditional way to indicate test methods in JUnit 3 is by prefixing their names with test. This is a very effective method for tagging certain methods in a class as having a special meaning, but the naming doesn’t scale very well (what if we want to add more tags for different frameworks?) and is rather inflexible (what if we want to pass additional parameters to the testing framework?). Annotations were formally added to the Java language in JDK 5, and TestNG made the choice to use annotations to annotate test classes. Here is the list of annotations that TestNG supports − Sr.No. Annotation & Description 1 @BeforeSuite The annotated method will be run only once before all tests in this suite have run. 2 @AfterSuite The annotated method will be run only once after all tests in this suite have run. 3 @BeforeClass The annotated method will be run only once before the first test method in the current class is invoked. 4 @AfterClass The annotated method will be run only once after all the test methods in the current class have run. 5 @BeforeTest The annotated method will be run before any test method belonging to the classes inside the <test> tag is run. 6 @AfterTest The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run. 7 @BeforeGroups The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked. 8 @AfterGroups The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked. 9 @BeforeMethod The annotated method will be run before each test method. 10 @AfterMethod The annotated method will be run after each test method. 11 @DataProvider Marks a method as supplying data for a test method. The annotated method must return an Object[ ][ ], where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation. 12 @Factory Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ]. 13 @Listeners Defines listeners on a test class. 14 @Parameters Describes how to pass parameters to a @Test method. 15 @Test Marks a class or a method as a part of the test. Benefits of Using Annotations Following are some of the benefits of using annotations − TestNG identifies the methods it is interested in, by looking up annotations. Hence, method names are not restricted to any pattern or format. We can pass additional parameters to annotations. Annotations are strongly typed, so the compiler will flag any mistakes right away. Test classes no longer need to extend anything (such as TestCase, for JUnit 3). Print Page Previous Next Advertisements ”;

TestNG – Home

TestNG Tutorial PDF Version Quick Guide Resources Job Search Discussion TestNG is a testing framework developed in the lines of JUnit and NUnit, however it introduces some new functionalities that make it more powerful and easier to use. TestNG is designed to cover all categories of tests: unit, functional, end-to-end, integration, etc., and it requires JDK 5 or higher. This tutorial provides a good understanding on TestNG framework needed to test an enterprise-level application to deliver it with robustness and reliability. Audience This tutorial is designed for software professionals interested in learning the features of TestNG Framework in simple and easy steps and implement it in practice. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of Java programming language, text editor, and execution of programs, etc. As you are going to use TestNG to handle all levels of Java project testing, it will be helpful if you have a prior knowledge of software development and software testing processes. Print Page Previous Next Advertisements ”;

TestNG – Environment

TestNG – Environment ”; Previous Next TestNG is a framework for Java, so the very first requirement is to have JDK installed in your machine. System Requirement JDK 1.7 or above. Memory No minimum requirement. Disk Space No minimum requirement. Operating System No minimum requirement. Step 1 – Verify Java Installation in Your Machine Open the console and execute a java command based on the operating system you have installed on your system. OS Task Command Windows Open Command Console c:> java -version Linux Open Command Terminal $ java -version Mac Open Terminal machine:~ joseph$ java -version Let”s verify the output for all the operating systems − OS Output Windows java version “15.0.2” 2021-01-19 Java(TM) SE Runtime Environment (build 15.0.2+7-27) Java HotSpot(TM) 64-Bit Server VM (build 15.0.2+7-27, mixed mode, sharing) Linux openjdk version “11.0.11” 2021-04-20 OpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2.20.04) OpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2.20.04, mixed mode, sharing) Mac java version “1.7.0_25” Java(TM) SE Runtime Environment (build 1.7.0_25-b15) Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode) If you do not have Java, install the Java Software Development Kit (SDK) from https://www.oracle.com/technetwork/java/javase/downloads/index.html. We are assuming Java 1.7.0_25 as the installed version for this tutorial. Step 2: Set JAVA Environment Set the JAVA_HOME environment variable to point to the base directory location, where Java is installed on your machine. For example, OS Output Windows Set the environment variable JAVA_HOME to C:Program FilesJavajdk15.0.2. Linux export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64/bin/java. You can also set this environment variable in the /etc/environment. Restart the machine after setting else it will be lost in the session. Mac export JAVA_HOME=/Library/Java/Home. Append Java compiler location to System Path. OS Output Windows Append the string C:Program FilesJavajdk1.7.0_25bin at the end of the system variable, Path. Linux export PATH=$PATH:$JAVA_HOME/bin/ Mac Not required Verify Java Installation using the command java -version as explained above. Step 3: Download TestNG Archive Download the latest version of TestNG jar file from http://www.testng.org or from here. At the time of writing this tutorial, we have downloaded testng-7.4.jar and copied it onto /work/testng folder. OS Archive name Windows testng-7.4.jar Linux testng-7.4.jar Mac testng-7.4.jar Step 4: Set TestNG Environment Set the TESTNG_HOME environment variable to point to the base directory location, where TestNG jar is stored on your machine. The following table shows how to set the environment variable in Windows, Linux, and Mac, assuming that we”ve stored testng-7.4.jar at the location /work/testng. OS Description Windows Set the environment variable TESTNG_HOME to C:testng. Linux export TESTNG_HOME=/work/testng. You can also set this environment variable in the /etc/environment. Restart the machine after setting else it will be lost in the session. Mac export TESTNG_HOME=/Library/testng Step 5: Set CLASSPATH Variable Set the CLASSPATH environment variable to point to the TestNG jar location. OS Description Windows Set the environment variable CLASSPATH to %CLASSPATH%;%TESTNG_HOME%testng-7.4.jar. Linux export CLASSPATH=$CLASSPATH:$TESTNG_HOME/testng-7.4.jar. This classpath is applicable only for current session. Once the current command termical closes, you will have to reset it. Mac export CLASSPATH=$CLASSPATH:$TESTNG_HOME/testng-7.4.jar. Step 6: Test TestNG Setup Create a java class file named TestNGSimpleTest at /work/testng/src import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class TestNGSimpleTest { @Test public void testAdd() { String str = “TestNG is working fine”; AssertEquals(“TestNG is working fine”, str); } } TestNG can be invoked in several different ways − With a testng.xml file. With ANT. From the command line. Let us invoke using the testng.xml file. Create an xml file with the name testng.xml in /work/testng/src to execute Test case(s). <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <classes> <class name = “TestNGSimpleTest”/> </classes> </test> </suite> Step 7: Verify the Result Compile the class using javac compiler as follows − /work/testng/src$ javac TestNGSimpleTest.java Now, invoke the testng.xml to see the result − /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. =============================================== Suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;

TestNG – Parallel Execution

TestNG – Parallel Execution ”; Previous Next TestNG allows to run tests parallelly or in separate threads in following ways: Parallel suites: If you are running several suite files (e.g. testng1.xml testng2.xml”), and you want each of these suites to be run in a separate thread. Use the following command line flag to specify the size of a thread pool: java org.testng.TestNG -suitethreadpoolsize 3 testng1.xml testng2.xml testng3.xml Parallel tests, classes and methods: Use parallel attribute on the <suite> tag respectively (for methods,test,classes, instances). <suite name=”My suite” parallel=”methods” thread-count=”5″> <suite name=”My suite” parallel=”tests” thread-count=”5″> <suite name=”My suite” parallel=”classes” thread-count=”5″> <suite name=”My suite” parallel=”instances” thread-count=”5″> Parallel testing is used heavily with Selenium because of the importance of cross-browser testing. With so many browsers in market today with a different version, create a browser matrix and run the tests parallelly. This will save us lot of time and other resources. Advantages and Disadvantages Following are some of the advantages of parallel testing using TestNG: It reduces time Allows multi-threaded tests Following are some of the disadvantages of parallel testing using TestNG Fails on dependent modules – Most of the times the tests are inter-dependent, hence failing chances are more. Program flow sequence – The tester should be well aware of the program flow to create parallel testing modules. Create Test Case Class Let us see an example to run test methods parallelly. Create a java class, say, TestParallel.java in /work/testng/src. import org.testng.annotations.Test; public class TestParallel { @Test public void method1() { System.out.println(“Inside method1()”); //Assert.assertEquals(message, messageUtil.printMessage()); } @Test public void method2() { System.out.println(“Inside method2()”); //Assert.assertEquals(message, messageUtil.printMessage()); } } The preceding test class contains two test methods which will run in separate threads. Create testng.xml Create testng.xml in /work/testng/src to execute test case(s). <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd”> <suite name = “Parallel Testing Suite”> <test name = “Parallel Tests” parallel = “methods”> <classes> <class name = “TestParallel” /> </classes> </test> </suite> Compile the TestParallel class using javac. /work/testng/src$ javac TestParallel.java Now, run testng.xml. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Inside method1() Inside method2() =============================================== Parallel Testing Suite Total tests run: 2, Passes: 2, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;

TestNG – Group Test

TestNG – Group Test ”; Previous Next Group test is a new innovative feature in TestNG, which doesn’t exist in JUnit framework. It permits you to dispatch methods into proper portions and perform sophisticated groupings of test methods. Not only can you declare those methods that belong to groups, but you can also specify groups that contain other groups. Then, TestNG can be invoked and asked to include a certain set of groups (or regular expressions), while excluding another set. Group tests provide maximum flexibility in how you partition your tests, and doesn”t require you to recompile anything if you want to run two different sets of tests back to back. Groups are specified in your testng.xml file using the <groups> tag. It can be found either under the <test> or <suite> tag. Groups specified in the <suite> tag apply to all the <test> tags underneath. Now, let”s take an example to see how group test works. Create a Class Create a java class to be tested, say, MessageUtil.java in /work/testng/src. /* * This class prints the given message on console. */ public class MessageUtil { private String message; // Constructor // @param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } // add “tutorialspoint” to the message public String salutationMessage() { message = “tutorialspoint” + message; System.out.println(message); return message; } // add “www.” to the message public String exitMessage() { message = “www.” + message; System.out.println(message); return message; } } Create Test Case Class Create a java test class, say, GroupTestExample.java in /work/testng/src. Add test methods, testPrintMessage() and testSalutationMessage(), to your test class. Group the test method in two categories − Check-in tests (checkintest) − These tests should be run before you submit new code. They should typically be fast and just make sure no basic functionality is broken. Functional tests (functest) − These tests should cover all the functionalities of your software and be run at least once a day, although ideally you would want to run them continuously. Following are the contents of GroupTestExample.java. import org.testng.Assert; import org.testng.annotations.Test; public class GroupTestExample { String message = “.com”; MessageUtil messageUtil = new MessageUtil(message); @Test(groups = { “functest”, “checkintest” }) public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); message = “.com”; Assert.assertEquals(message, messageUtil.printMessage()); } @Test(groups = { “checkintest” }) public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “tutorialspoint” + “.com”; Assert.assertEquals(message, messageUtil.salutationMessage()); } @Test(groups = { “functest” }) public void testingExitMessage() { System.out.println(“Inside testExitMessage()”); message = “www.” + “tutorialspoint”+”.com”; Assert.assertEquals(message, messageUtil.exitMessage()); } } Create testng.xml Create testng.xml in /work/testng/src, to execute test case(s). Here, we would be executing only those tests, that belong to the group functest. <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <groups> <run> <include name = “functest” /> </run> </groups> <classes> <class name = “GroupTestExample” /> </classes> </test> </suite> Compile the MessageUtil, Test case classes using javac. /work/testng/src$ javac MessageUtil.java GroupTestExample.java Now, run the testng.xml, which will run only the method testPrintMessage(), as it belongs to the group functest. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Only the method testPrintMessage() is executed. Inside testPrintMessage() .com Inside testExitMessage() www..com =============================================== Suite1 Total tests run: 2, Failures: 1, Skips: 0 =============================================== Group of Groups Groups can also include other groups. These groups are called MetaGroups. For example, you might want to define a group all that includes checkintest and functest. Let”s modify our testng.xml file as follows − <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <groups> <define name = “all”> <include name = “functest”/> <include name = “checkintest”/> </define> <run> <include name = “all”/> </run> </groups> <classes> <class name = “GroupTestExample” /> </classes> </test> </suite> Executing the above testng.xml will execute all the three tests and will give you the following result − Inside testPrintMessage() .com Inside testSalutationMessage() tutorialspoint.com Inside testExitMessage() www.tutorialspoint.com =============================================== Suite1 Total tests run: 3, Failures: 0, Skips: 0 =============================================== Exclusion Groups You can ignore a group by using the <exclude> tag as shown below − <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <groups> <define name = “all”> <exclude name = “functest”/> <include name = “checkintest”/> </define> <run> <include name = “all”/> </run> </groups> <classes> <class name = “GroupTestExample” /> </classes> </test> </suite> Print Page Previous Next Advertisements ”;

TestNG – Executing Tests

TestNG – Executing Tests ”; Previous Next The test cases are executed using TestNG class. This class is the main entry point for running tests in the TestNG framework. Users can create their own TestNG object and invoke it in many different ways such as − On an existing testng.xml. On a synthetic testng.xml, created entirely from Java. By directly setting the test classes. You can also define which groups to include or exclude, assign parameters, etc. The command line parameters are − -d outputdir: specify the output directory. -testclass class_name: specifies one or several class names. -testjar jar_name: specifies the jar containing the tests. -sourcedir src1;src2: ; separated list of source directories (used only when javadoc annotations are used). -target -groups -testrunfactory -listener We will create the TestNG object an existing testng.xml in our example below. Create a Class Create a java class to be tested, say, MessageUtil.java in /work/testng/src. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } } Create Test Case Class Create a java test class, say, SampleTest.java. Add a test method testPrintMessage() to your test class. Add an Annotation @Test to method testPrintMessage(). Implement the test condition and check the condition using assertEquals API of TestNG. Create a java class file called SampleTest.java in /work/testng/src. import org.testng.Assert; import org.testng.annotations.Test; public class SampleTest { String message = “Hello World”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { Assert.assertEquals(message, messageUtil.printMessage()); } } Create testng.xml Next, let”s create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database). <?xml version = “1.0” encoding = “UTF-8”?> <suite name = “Sample test Suite”> <test name = “Sample test”> <classes> <class name = “SampleTest” /> </classes> </test> </suite> Compile the test case using javac. /work/testng/src$ javac MessageUtil.java SampleTest.java Now, run the testng.xml, which will run the test case defined in <test> tag. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Hello World =============================================== Sample test Suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;