This post illustrates some of the feature of
TestNG. The code example is available at
GitHub in the
Java-TestNG directory. We use
maven. Therefore, the
configuration will located in the
pom.xml.
Source Code
We use a very simple class returning integers for testing purposes:
public class Generate {
private Generate() { }
public static int aOne() {
return 1;
}
public static int aTwo() {
return 2;
}
...
}
Test Code
The test code for the above class is the following:
public class GenerateNGTest {
public GenerateNGTest() { }
@Test(groups = {"testGroupA"})
public void testAOne() {
assertEquals(1,Generate.aOne());
}
@Test(groups = {"testGroupA", "testGroupB", "windows.QTests"})
public void testATwo() {
assertEquals(2,Generate.aTwo());
}
@Test(groups = {"testGroupA", "testGroupC", "windows.PTests"})
public void testAThree() {
assertEquals(3,Generate.aThree());
}
@Parameters({ "testNgParam" })
@Test(groups = {"testGroupA"})
public void testAFour(@Optional("4") String testNgParam) {
assertEquals(Integer.parseInt(testNgParam),Generate.aFour());
}
@Parameters({ "testNgParam2" })
@Test(groups = {"testGroupA"})
public void testASix(String testNgParam2) {
assertEquals(Integer.parseInt(testNgParam2),Generate.aSix());
}
public class DataForTests {
@DataProvider(name = "forTestAFive")
public Object[][] forTestAFive() {
return new Object[][] {
{ new Integer(5) },
{ new Integer(6) }
};
}
}
@Test(dataProvider = "forTestAFive", dataProviderClass = DataForTests.class)
public void testAFive(int param) {
assertEquals(param,Generate.aFive());
}
@Test(dependsOnGroups = { "windows.*" })
public void testASeven() {
assertEquals(7,Generate.aSeven());
}
}
- Some test groups are defined for test methods. These can be activated in the configuration described further.
- The testAFour() method takes in a parameter and defaults to 4 if none is provided.
- Rather than setting parameters in the configuration, one can define a DataForTests class and use it to pass parameters as in the testAFive() method.
In this example, we do not cover factories and automatic test generation, programmatic executions of tests and test methods interceptors.
Configuration
In the
pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14</version>
<configuration>
<groups>testGroupA</groups>
<systemPropertyVariables>
<testNgParam>4</testNgParam>
<testNgParam2>6</testNgParam2>
</systemPropertyVariables>
<parallel>methods</parallel>
<threadCount>2</threadCount>
</configuration>
</plugin>
We activate tests belonging to
testGroupA and we pass parameter values for
testNgParam and
testNgParam2. We also let TestNG run each test method in parallel using 2 threads. This can significantly accelerate the testing phase when compiling the project.
No comments:
Post a Comment