TestNG – Useful Resources

TestNG – Useful Resources ”; Previous Next The following resources contain additional information on TestNG. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Selenium And Java Advanced Course with Live Project Best Seller 296 Lectures 146 hours Arun Motoori More Detail TestNG Complete Bootcamp For Beginners 39 Lectures 4.5 hours Lets Kode It More Detail Selenium WebDriver 4 with Java – Zero To Hero Most Popular 294 Lectures 41.5 hours Lets Kode It More Detail தமிழ் மொழியில் Selenium கற்றுக்கொள்ளுங்கள் | Learn Selenium 35 Lectures 8.5 hours Programming Line More Detail Learn TestNG 15 Lectures 1.5 hours Quaatso Learning More Detail The Complete Selenium WebDriver with Java Course Most Popular 202 Lectures 21 hours Dezlearn Education More Detail Print Page Previous Next Advertisements ”;

TestNG – Overview

TestNG – Overview ”; Previous Next Testing is the process of checking the functionality of an application to ensure it works as per requirements. Unit testing comes into picture at the developer level where adequate measures are taken to test every single entity (class or method) to ensure the final product meets the requirements. JUnit has driven developers to understand the usefulness of tests, especially of unit tests, when compared to any other testing framework. Leveraging a rather simple, pragmatic, and strict architecture, JUnit has been able to “infect” great number of developers. Do take a look at our tutorial on JUnit to have a good understanding of its features. JUnit, at the same time, has some shortcomings as well, which are listed below − Initially designed to enable unit testing only, now used for all kinds of testing. Cannot do dependency testing. Poor configuration control (setUp/tearDown). Intrusive (forces you to extend classes and name your methods a certain way). Static programming model (forces you to recompile unnecessarily). The management of different suites of tests in complex projects can be very tricky. What is TestNG? Definition of TestNG as per its documentation is as follows − TestNG is a testing framework inspired from JUnit and NUnit, but introducing some new functionalities that make it more powerful and easier to use. TestNG is an open source automated testing framework; where NG means NextGeneration. TestNG is similar to JUnit (especially JUnit 4), but it is not a JUnit extension. It is inspired by JUnit. It is designed to be better than JUnit, especially when testing integrated classes. The creator of TestNG is Cedric Beust. Eliminating most of the limitations of the older framework, TestNG gives the developer the ability to write more flexible and powerful tests. As it heavily borrows from Java Annotations (introduced with JDK 5.0) to define tests, it can also show you how to use this new feature of the Java language in a real production environment. TestNG Features Supports annotations. TestNG uses more Java and OO features. Supports testing integrated classes (e.g., by default, no need to create a new test class instance for every test method). Separates compile-time test code from run-time configuration/data info. Flexible runtime configuration. Introduces ‘test groups’. Once you have compiled your tests, you can just ask TestNG to run all the “front-end” tests, or “fast”, “slow”, “database” tests, etc. Supports Dependent test methods, parallel testing, load testing, and partial failure. Flexible plug-in API. Support for multi threaded testing. Print Page Previous Next Advertisements ”;

TestNG – TestNG – vs JUnit

TestNG – vs JUnit ”; Previous Next JUnit and TestNG are the most popular testing frameworks for Java applications. Both of these frameworks are easy to use. So when it comes to chose the testing framework for your application, it’s better to have a high-level idea of what features are present in one or the other and then take the informed decision based on your project requirements. JUnit vs TestNG JUnit current version is 5.7.1 and it’s still evolving and working on to include more features. TestNG current version is 7.4.0 and it’s mature and features rich. Following table compares JUnit vs TestNG on different features. The table excludes very specific or common features that are present in both these frameworks, such as testing exceptions, timeout settings, lifecycle callback methods etc. Feature JUnit TestNG Conclusion Annotations Annotations Based Annotations Based Both JUnit 5 and TestNG are annotation based. They are similar in nature and behavior. Ease of Use JUnit 5 is built into various modules, you need JUnit Platform and JUnit Jupiter to write test cases. If you want more features such as Parameterized Tests then you need to add junit-jupiter-params module. Single module to get all TestNG feature. TestNG is better in terms of ease of use. IDE Support Supported on major IDEs such as Eclipse and IntelliJ IDEA. Supported on major IDEs such as Eclipse and IntelliJ IDEA. Both of them are similar and provides easy integration with major IDEs. Data Provider Supports multiple ways to provide test data, such as methods, Enum, CSV, CSV Files etc. Supports data provider methods and from test suite xml file. JUnit is better for injecting test methods input data Test Suite In JUnit, Test Suite is run using @RunWith and @Suite annotations. TestNG uses an XML file to run Suite test. HTML Reports JUnit need external plugin maven-surefire-report-plugin to generate HTML reports. TestNG automatically creates HTML reports for the test run. TestNG HTML reports look outdated but it’s simple to use. If you have to share HTML reports with others, I would suggest to use JUnit. Running from Java Main Method We can use JUnit 5 launcher API to run tests from java main method. We can use TestNG run() method to execute tests from the java main method. Both of them supports execution of test cases from java main method. Assertions JUnit provides enough assertion methods to compare expected and actual test results. TestNG provides enough assertion methods to compare expected and actual test results. Both of them are similar in terms of Assertions support. Assumptions JUnit supports assumptions to skip tests based on certain conditions. TestNG doesn’t support assumptions. JUnit is better if you want to skip tests based on conditions. Test Order Junit does not support Test Order. TestNG supports Test Order for ordering test methods according to priority attribute. TestNG is better when you want to execute tests in specific order. Disable Tests JUnit supports many ways to disable and enable tests. For example, based on OS, JRE, system properties. TestNG supports disabling tests but it’s limited in functionality. JUnit is better when you want to disable or enable tests based on conditions. Parallel Execution JUnit 5 doesn’t support parallel execution yet. TestNG supports parallel execution if run through XML suite. TestNG is better for parallel execution as of now, JUnit 5 development is going on to support this feature. Listeners JUnit supports listeners through Launcher API, there is no mechanism to add listeners using annotations. TestNG supports various types of listeners and can be added using annotations. TestNG listener support is much better compared to JUnit 5. Print Page Previous Next Advertisements ”;

TestNG – Plug with ANT

TestNG – Plug with ANT ”; Previous Next In this chapter, we will demonstrate how to run TestNG using ANT. Let”s follow the steps given below − Step 1: Download Apache Ant Download the latest version of Apache Ant OS Archive Name Windows apache-ant-1.10.10-bin.zip Linux apache-ant-1.10.10-bin.tar.gz Mac apache-ant-1.10.10-bin.tar.gz Step 2: Set Ant Environment Set the ANT_HOME environment variable to point to the base directory location, where ANT libraries are stored on your machine. Let’s assume we”ve stored the Ant libraries in the folder apache-ant-1.8.4 folder. OS Output Windows Set the environment variable ANT_HOME to C:Program FilesApache Software Foundationapache-ant-1.10.10 Linux Export ANT_HOME=/usr/local/apache-ant-1.10.10 Mac Export ANT_HOME=/Library/apache-ant-1.10.10 Append Ant compiler location to System Path as follows − OS Description Windows Append the string %ANT_HOMEbin at the end of the system variable, Path. Linux export PATH=$PATH:$ANT_HOME/bin/ Mac Not required. Step 3: Download TestNG Archive Download the required jar files http://www.testng.org. OS Archive name Windows testng-7.4.jar Linux testng-7.4.jar Mac testng-7.4.jar Step 4: Create Project Structure Create a folder TestNGWithAnt in /work/testng/src. Create a folder src in /work/testng/src/TestNGWithAnt. Create a folder test in /work/testng/src/TestNGWithAnt. Create a folder lib in /work/testng/src/TestNGWithAnt. Create MessageUtil class in /work/testng/src/TestNGWithAnt/src folder. /* * 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 void printMessage() { System.out.println(message); return message; } // add “Hi!” to the message public String salutationMessage() { message = “Hi!” + message; System.out.println(message); return message; } } Create TestMessageUtil class in /work/testng/src/TestNGWithAnt/src folder. import org.testng.Assert; import org.testng.annotations.Test; public class TestMessageUtil { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); Assert.assertEquals(message,messageUtil.printMessage()); } @Test public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Manisha”; Assert.assertEquals(message,messageUtil.salutationMessage()); } } Copy testng-7.4.jar in /work/testng/src/TestNGWithAnt/lib folder. Create ANT build.xml First, we need to define the TestNG Ant task as follows − <taskdef name = “testng” classname = “org.testng.TestNGAntTask”> <classpath> <pathelement location = “lib/testng-7.4.jar”/> </classpath> </taskdef> Then, we”ll be using <testng> task in Ant to execute our TestNG test cases. The build.xml file is as follows − <project name = “TestNGTest” default = “test” basedir = “.”> <!– Define <testng> task –> <taskdef name = “testng” classname = “org.testng.TestNGAntTask”> <classpath> <pathelement location = “lib/testng-7.4.jar”/> </classpath> </taskdef> <property name = “testdir” location = “test” /> <property name = “srcdir” location = “src” /> <property name = “libdir” location = “lib” /> <property name = “full-compile” value=”true” /> <path id = “classpath.base”/> <path id = “classpath.test”> <fileset dir = “${libdir}”> <include name = “**/*.jar” /> </fileset> <pathelement location = “${testdir}” /> <pathelement location = “${srcdir}” /> <path refid = “classpath.base” /> </path> <target name = “clean” > <delete verbose=”${full-compile}”> <fileset dir = “${testdir}” includes=”**/*.class” /> </delete> </target> <target name = “compile” depends=”clean”> <javac srcdir = “${srcdir}” destdir = “${testdir}” verbose=”${full-compile}”> <classpath refid = “classpath.test”/> </javac> </target> <target name = “test” depends=”compile”> <testng outputdir = “${testdir}” classpathref=”classpath.test”> <xmlfileset dir = “${srcdir}” includes=”testng.xml”/> </testng> </target> </project> Run the following Ant command. /work/testng/src/TestNGWithAnt$ ant Verify the output. test: [testng] [TestNG] Running: [testng] /work/testng/src/TestNGWithAnt/src/testng.xml [testng] [testng] Inside testPrintMessage() [testng] Manisha [testng] Inside testSalutationMessage() [testng] Hi!Manisha [testng] [testng] =============================================== [testng] Plug ANT test Suite [testng] Total tests run: 2, Failures: 0, Skips: 0 [testng] =============================================== [testng] BUILD SUCCESSFUL Total time: 1 second Print Page Previous Next Advertisements ”;

TestNG – Quick Guide

TestNG – Quick Guide ”; Previous Next TestNG – Overview Testing is the process of checking the functionality of an application to ensure it works as per requirements. Unit testing comes into picture at the developer level where adequate measures are taken to test every single entity (class or method) to ensure the final product meets the requirements. JUnit has driven developers to understand the usefulness of tests, especially of unit tests, when compared to any other testing framework. Leveraging a rather simple, pragmatic, and strict architecture, JUnit has been able to “infect” great number of developers. Do take a look at our tutorial on JUnit to have a good understanding of its features. JUnit, at the same time, has some shortcomings as well, which are listed below − Initially designed to enable unit testing only, now used for all kinds of testing. Cannot do dependency testing. Poor configuration control (setUp/tearDown). Intrusive (forces you to extend classes and name your methods a certain way). Static programming model (forces you to recompile unnecessarily). The management of different suites of tests in complex projects can be very tricky. What is TestNG? Definition of TestNG as per its documentation is as follows − TestNG is a testing framework inspired from JUnit and NUnit, but introducing some new functionalities that make it more powerful and easier to use. TestNG is an open source automated testing framework; where NG means NextGeneration. TestNG is similar to JUnit (especially JUnit 4), but it is not a JUnit extension. It is inspired by JUnit. It is designed to be better than JUnit, especially when testing integrated classes. The creator of TestNG is Cedric Beust. Eliminating most of the limitations of the older framework, TestNG gives the developer the ability to write more flexible and powerful tests. As it heavily borrows from Java Annotations (introduced with JDK 5.0) to define tests, it can also show you how to use this new feature of the Java language in a real production environment. TestNG Features Supports annotations. TestNG uses more Java and OO features. Supports testing integrated classes (e.g., by default, no need to create a new test class instance for every test method). Separates compile-time test code from run-time configuration/data info. Flexible runtime configuration. Introduces ‘test groups’. Once you have compiled your tests, you can just ask TestNG to run all the “front-end” tests, or “fast”, “slow”, “database” tests, etc. Supports Dependent test methods, parallel testing, load testing, and partial failure. Flexible plug-in API. Support for multi threaded testing. TestNG – Environment TestNG is a framework for Java, so the very first requirement is to have JDK installed in your machine. System Requirement JDK 1.5 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 “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) Linux 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) 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 FilesJavajdk1.7.0_25. Linux Export JAVA_HOME=/usr/local/java-current. 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. At the time of writing this tutorial, we have downloaded testng-6.8.jar and copied it onto C:> TestNG folder. OS Archive name Windows testng-6.8.jar Linux testng-6.8.jar Mac testng-6.8.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-6.8.jar at the location C:>TestNG. OS Description Windows Set the environment variable TESTNG_HOME to C:TESTNG. Linux Export TESTNG_HOME=/usr/local/TESTNG 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-6.8.jar. Linux Export CLASSPATH=$CLASSPATH:$TESTNG_HOME/testng-6.8.jar. Mac Export CLASSPATH=$CLASSPATH:$TESTNG_HOME/testng-6.8.jar. Step 6: Test TestNG Setup Create a java class file named TestNGSimpleTest at C:>TestNG_WORKSPACE. 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 C:>TestNG_WORKSPACE 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 − C:TestNG_WORKSPACE>javac TestNGSimpleTest.java Now, invoke the testng.xml to see the result − C:TestNG_WORKSPACE>java -cp “C:TestNG_WORKSPACE” org.testng.TestNG testng.xml Verify the output. =============================================== Suite1 Total tests run: 1, Failures: 0, Skips: 0 =============================================== TestNG – Writing Tests Writing a test in TestNG basically

TestNG – Writing Tests

TestNG – Writing Tests ”; Previous Next Writing a test in TestNG basically involves the following steps − Write the business logic of your test and insert TestNG annotations in your code. Add the information about your test (e.g. the class name, the groups you wish to run, etc.) in a testng.xml file or in build.xml. Run TestNG. Here, we will see one complete example of TestNG testing using POJO class, Business logic class and a test xml, which will be run by TestNG. Create EmployeeDetails.java in /work/testng/src, which is a POJO class. public class EmployeeDetails { private String name; private double monthlySalary; private int age; // @return the name public String getName() { return name; } // @param name the name to set public void setName(String name) { this.name = name; } // @return the monthlySalary public double getMonthlySalary() { return monthlySalary; } // @param monthlySalary the monthlySalary to set public void setMonthlySalary(double monthlySalary) { this.monthlySalary = monthlySalary; } // @return the age public int getAge() { return age; } // @param age the age to set public void setAge(int age) { this.age = age; } } EmployeeDetails class is used to − get/set the value of employee”s name. get/set the value of employee”s monthly salary. get/set the value of employee”s age. Create an EmpBusinessLogic.java in /work/testng/src, which contains business logic. public class EmpBusinessLogic { // Calculate the yearly salary of employee public double calculateYearlySalary(EmployeeDetails employeeDetails) { double yearlySalary = 0; yearlySalary = employeeDetails.getMonthlySalary() * 12; return yearlySalary; } // Calculate the appraisal amount of employee public double calculateAppraisal(EmployeeDetails employeeDetails) { double appraisal = 0; if(employeeDetails.getMonthlySalary() < 10000) { appraisal = 500; } else { appraisal = 1000; } return appraisal; } } EmpBusinessLogic class is used for calculating − the yearly salary of employee. the appraisal amount of employee. Now, let”s create a TestNG class called TestEmployeeDetails.java in /work/testng/src. A TestNG class is a Java class that contains at least one TestNG annotation. This class contains test cases to be tested. A TestNG test can be configured by @BeforeXXX and @AfterXXX annotations (we will see this in the chapter TestNG – Execution Procedure), which allows to perform some Java logic before and after a certain point. import org.testng.Assert; import org.testng.annotations.Test; public class TestEmployeeDetails { EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic(); EmployeeDetails employee = new EmployeeDetails(); @Test public void testCalculateAppriasal() { employee.setName(“Rajeev”); employee.setAge(25); employee.setMonthlySalary(8000); double appraisal = empBusinessLogic.calculateAppraisal(employee); Assert.assertEquals(500, appraisal, 0.0, “500”); } // Test to check yearly salary @Test public void testCalculateYearlySalary() { employee.setName(“Rajeev”); employee.setAge(25); employee.setMonthlySalary(8000); double salary = empBusinessLogic.calculateYearlySalary(employee); Assert.assertEquals(96000, salary, 0.0, “8000”); } } TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It does the following − Tests the yearly salary of the employee. Tests the appraisal amount of the employee. Before you can run the tests, you must configure TestNG using a special XML file, conventionally named testng.xml. The syntax for this file is very simple, and its contents are as shown below. Create this file in /work/testng/src. <?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 = “TestEmployeeDetails”/> </classes> </test> </suite> Details of the above file are as follows − A suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag. Tag <test> represents one test and can contain one or more TestNG classes. <class> tag represents a TestNG class. It is a Java class that contains at least one TestNG annotation. It can contain one or more test methods. Compile the Test case classes using javac. /work/testng/src$ javac EmployeeDetails.java EmpBusinessLogic.java TestEmployeeDetails.java Now TestNG with the following command − /work/testng/src$ java org.testng.TestNG testng.xml If all has been done correctly, you should see the results of your tests in the console. Furthermore, TestNG creates a very nice HTML report in a folder called test-output that is automatically created in the current directory. If you open it and load index.html, you will see a page similar to the one in the image below − Print Page Previous Next Advertisements ”;

TestNG – Dependency Test

TestNG – Dependency Test ”; Previous Next Sometimes, you may need to invoke methods in a test case in a particular order, or you may want to share some data and state between methods. This kind of dependency is supported by TestNG, as it supports the declaration of explicit dependencies between test methods. TestNG allows you to specify dependencies either with − Using attribute dependsOnMethods in @Test annotations, OR. Using attribute dependsOnGroups in @Test annotations. Example Using dependsOnMethods Create a Class Create a java class to be tested, say, MessageUtil.java in /work/testng/src. 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 “Hi!” to the message public String salutationMessage() { message = “Hi!” + message; System.out.println(message); return message; } } Create Test Case Class Create a java test class, say, DependencyTestUsingAnnotation.java in /work/testng/src. Add test methods, testPrintMessage() and testSalutationMessage(), and initEnvironmentTest(), to your test class. Add attribute dependsOnMethods = {“initEnvironmentTest”} to the @Test annotation of testSalutationMessage() method. Following are the DependencyTestUsingAnnotation.java contents. import org.testng.Assert; import org.testng.annotations.Test; public class DependencyTestUsingAnnotation { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); message = “Manisha”; Assert.assertEquals(message, messageUtil.printMessage()); } @Test(dependsOnMethods = { “initEnvironmentTest” }) public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Manisha”; Assert.assertEquals(message, messageUtil.salutationMessage()); } @Test public void initEnvironmentTest() { System.out.println(“This is initEnvironmentTest”); } } 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”> <classes> <class name = “DependencyTestUsingAnnotation” /> </classes> </test> </suite> Compile the MessageUtil, Test case classes using javac. /work/testng/src$ javac MessageUtil.java DependencyTestUsingAnnotation.java Now, run the testng.xml, which will run the testSalutationMessage() method only after the execution of initEnvironmentTest() method. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. This is initEnvironmentTest Inside testPrintMessage() Manisha Inside testSalutationMessage() Hi!Manisha =============================================== Suite1 Total tests run: 3, Failures: 0, Skips: 0 =============================================== Example Using dependsOnGroups You can also have methods that depend on entire groups. Let”s have an example to demonstrate this. Create a Class Create a java class to be tested, say, MessageUtil.java in /work/testng/src. 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 “Hi!” to the message public String salutationMessage() { message = “Hi!” + message; System.out.println(message); return message; } } Create Test Case Class Create a java test class, say, DependencyTestUsingAnnotation.java. Add test methods, testPrintMessage() testSalutationMessage(), and initEnvironmentTest() to your test class, and add them to the group “init”. Add the attribute dependsOnMethods = {“init.*”} to the @Test annotation of testSalutationMessage() method. Create a java class file named DependencyTestUsingAnnotation.java in /work/testng/src. import org.testng.Assert; import org.testng.annotations.Test; public class DependencyTestUsingAnnotation { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test(groups = { “init” }) public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); message = “Manisha”; Assert.assertEquals(message, messageUtil.printMessage()); } @Test(dependsOnGroups = { “init.*” }) public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Manisha”; Assert.assertEquals(message, messageUtil.salutationMessage()); } @Test(groups = { “init” }) public void initEnvironmentTest() { System.out.println(“This is initEnvironmentTest”); } } In this example, testSalutationMessage() is declared as depending on any group, matching the regular expression “init.*”, which guarantees that the methods testPrintMessage() and initEnvironmentTest() will always be invoked before testSalutationMessage(). If a method depended upon fails, and you have a hard dependency on it (alwaysRun=false, which is the default), the methods that depend on it are not marked as FAIL but as SKIP. Skipped methods will be reported as such in the final report (in a color that is neither Red nor Green in HTML), which is important since skipped methods are not necessarily failures. 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”> <classes> <class name = “DependencyTestUsingAnnotation” /> </classes> </test> </suite> Compile the MessageUtil, Test case classes using javac. /work/testng/src$ javac MessageUtil.java DependencyTestUsingAnnotation.java Now, run the testng.xml, which will run the testSalutationMessage() method only after the execution of initEnvironmentTest() method. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. This is initEnvironmentTest Inside testPrintMessage() Manisha Inside testSalutationMessage() Hi!Manisha =============================================== Suite1 Total tests run: 3, Failures: 0, Skips: 0 =============================================== dependsOnGroups Vs dependsOnMethods On using groups, we are no longer exposed to refactoring problems. As long as we don’t modify the dependsOnGroups or groups attributes, our tests will keep running with the proper dependencies set up. Whenever a new method needs to be added in the dependency graph, all we need to do is put it in the right group and make sure it depends on the correct group. We don’t need to modify any other method. Print Page Previous Next Advertisements ”;

TestNG – Run JUnit Tests

TestNG – Run JUnit Tests ”; Previous Next Now that you have understood TestNG and its various tests, you must be worried by now as to how to refactor your existing JUnit code. There”s no need to worry, as TestNG provides a way to shift from JUnit to TestNG at your own pace. You can execute your existing JUnit test cases using TestNG. TestNG can automatically recognize and run JUnit tests, so that you can use TestNG as a runner for all your existing tests and write new tests using TestNG. All you have to do is to put JUnit library on the TestNG classpath, so it can find and use JUnit classes, change your test runner from JUnit to TestNG in Ant, and then run TestNG in “mixed” mode. This way, you can have all your tests in the same project, even in the same package, and start using TestNG. This approach also allows you to convert your existing JUnit tests to TestNG incrementally. Let us have an example to demonstrate this amazing ability of TestNG. Create JUnit Test Case Class Create a java class, which is a JUnit test class, TestJunit.java in /work/testng/src. import org.junit.Test; import static org.testng.AssertJUnit.*; public class TestJunit { @Test public void testAdd() { String str = “Junit testing using TestNG”; assertEquals(“Junit testing using TestNG”,str); } } Now, let”s write the testng.xml in /work/testng/src, which would contain the <suite> tag as follows − <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd”> <suite name = “Converted JUnit suite” > <test name = “JUnitTests” junit=”true”> <classes> <class name = “TestJunit” /> </classes> </test> </suite> To execute the JUnit test cases, define the property junit=”true” as in the xml above. The JUnit test case class TestJunit is defined in class name. For JUnit 4, TestNG will use the org.junit.runner.JUnitCore runner to run your tests. Compile all java classes using javac. /work/testng/src$ javac TestJunit.java Now, run testng.xml, which will run the JUnit test case as TestNG. /work/testng/src$java -cp “/work/testng/src/junit-4.13.2.jar:/work/testng/src/hamcrest-core-1.3.jar” org.testng.TestNG testng.xml Here, we have placed the dependent JAR files junit-4.13.2.jar and hamcrest-core-1.3.jar under /work/testng/src/. Verify the output. =============================================== Converted JUnit suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;

TestNG – Suite Test

TestNG – Suite Test ”; Previous Next A test suite is a collection of test cases intended to test a behavior or a set of behaviors of software program. In TestNG, we cannot define a suite in testing source code, but it is represented by one XML file, as suite is the feature of execution. It also allows flexible configuration of the tests to be run. A suite can contain one or more tests and is defined by the <suite> tag. <suite> is the root tag of your testng.xml. It describes a test suite, which in turn is made of several <test> sections. The following table lists all the legal attributes that <suite> accepts. Sr.No. Attribute & Description 1 name The name of this suite. It is a mandatory attribute. 2 verbose The level or verbosity for this run. 3 parallel Whether TestNG should run different threads to run this suite. 4 thread-count The number of threads to use, if parallel mode is enabled (ignored other-wise). 5 annotations The type of annotations you are using in your tests. 6 time-out The default timeout that will be used on all the test methods found in this test. In this chapter, we will show you an example having two test classes, Test1 & Test2, to run together using Test Suite. 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 “Hi!” to the message public String salutationMessage() { message = “Hi!” + message; System.out.println(message); return message; } } Create Test Case Classes Create a java class file named Test1.java in /work/testng/src. import org.testng.Assert; import org.testng.annotations.Test; public class Test1 { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); Assert.assertEquals(message, messageUtil.printMessage()); } } Create a java class file named Test2.java in /work/testng/src . import org.testng.Assert; import org.testng.annotations.Test; public class Test2 { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Manisha”; Assert.assertEquals(message,messageUtil.salutationMessage()); } } Now, let”s write the testng.xml in /work/testng/src , which would contain the <suite> tag as follows − <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “exampletest1”> <classes> <class name = “Test1” /> </classes> </test> <test name = “exampletest2”> <classes> <class name = “Test2″ /> </classes> </test> </suite> Suite1 includes exampletest1 and exampletest2. Compile all java classes using javac. /work/testng/src$ javac MessageUtil.java Test1.java Test2.java Now, run the testng.xml, which will run the test case defined in the provided Test Case class. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Manisha Inside testSalutationMessage() Hi!Manisha =============================================== Suite1 Total tests run: 2, Passes: 2, Failures: 0, Skips: 0 =============================================== You can also check the test-output folder. Under the Suite1 folder, you can see two html files created, exampletest1.html and exampletest2.html, which would look as follows − 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