Writing and executing a simple TestNG
program is mainly 3 step process.
testng.xml
or in build.xml
Brief explanation of example (what needs to be tested):
We have a RandomNumberGenerator
class which has a method generateFourDigitPin
that generates a 4 digit PIN and returns as int
. So here we want to test whether that random number is if of 4 digits or not. Below is the code:
Class to be tested:
package example.helloworld;
public class RandomNumberGenerator {
public int generateFourDigitPin(){
return (int)(Math.random() * 10000);
}
}
The TestNG test class:
package example.helloworld;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestRandomNumberGenerator {
RandomNumberGenerator rng = null;
@BeforeClass
public void deSetup(){
rng = new RandomNumberGenerator();
}
@Test
public void testGenerateFourDigitPin(){
int randomNumber = rng.generateFourDigitPin();
Assert.assertEquals(4, String.valueOf(randomNumber).length());
}
@AfterClass
public void doCleanup(){
//cleanup stuff goes here
}
}
Ther testng.xml:
<suite name="Hello World">
<test name="Random Number Generator Test">
<classes>
<class name="example.helloworld.TestRandomNumberGenerator" />
</classes>
</test>
</suite>