TestNG basic usage and its details are discussed in this post. TestNG is a testing framework used for Unit testing and Integration Testing. It is easy to use framework and more powerful by overcoming the limitations of Junit, such as:
What TestNG supports when compared to Junit:
- Groups — Execute tests based on Groups.
- Test dependency — Can make 1 or more tests depending on other tests
- Parallel execution — Tests can be executed in parallel
- Data driven testing — Separate Annotation supporting data driven testing
- Many other annotations when compared to Junit.
Pre requisites to use TestNG:
- TestNG requires JDK 7 or higher version.
- Java 8 can be downloaded from here. Java 8
TestNG usage in code:
- Download TestNG jar
- Use TestNG annotations over test/business logic in java code
- Use a testng.xml file to add classes/packages that has tests you want to run
1. Download TestNG jar
- For direct download, refer TestNG official site and then download.jar file or download from maven repository, mvnrepo
- Add this testng.jar file to the libraries in IDE.
- For Maven dependency, if you are using maven project, here is the code which needs to be placed under <dependencies> tag in pom.xml
2. Use TestNG annotations in code
- For Basic understanding covering only 2 annotations in this post. @BeforeClass, @Test. Will provide more details on other Annotations in next Post.
- The below sample code has two methods,
setUp() – used BeforeClass annotation, so this method will invoke after test class has been started and before any test method runs.
sample() – used Test annotation, so it will run always.
Note: In testNG class, there is no need to extend a class like Junit.
Here is the code snippet.
3. Use testng.xml file to add classes
- XML file is used to run the tests.
- XML file has suite, represented by <suite> tag, it can contain one or more tests.
- A test is represented by <test> tag, it can contain one or more TestNG classes.
- A class is a java class represented by <class> tag, contains at least one TestNG annotations.
Created testng.xml named as ‘sample.xml‘
Included the above class ‘SampleTestngUsage‘ placed in package com.exploreselenium.
When executed this testng.xml file, it will execute setUp & sample methods in SampleTestngUsage class.
Running testng.xml (using IntelliJ IDE)
- Right click on testng.xml (sample.xml) and then select run option in context menu.
- It will run tests in classes added in sample.xml.
Below screenshot represents the results of the execution and also project structure.
Note: To generate test-output while executing from IntelliJ IDE, need to check ‘use default reports’ check box in Edit configurations.
So basically, here we tried to explain TestNG basic usage in code, its details and how to execute tests from testng.xml file.