Skip to content

Instantly share code, notes, and snippets.

@KrishnaKotari
Last active August 29, 2015 14:18
Show Gist options
  • Save KrishnaKotari/8db47259543595cacc9b to your computer and use it in GitHub Desktop.
Save KrishnaKotari/8db47259543595cacc9b to your computer and use it in GitHub Desktop.
Classes related to Unit testing with TestNG
/**
*
* @author Krishna
*
*/
public class BusinessClass {
private int offset;
public void init(int offset) {
this.offset = offset;
}
/**
* Method to perform complicated add operation
*
* @param a
* @param b
* @return
*/
public Integer complicatedAddOp(Integer a, Integer b) {
// Just throw an exception if either of them are null
if (null == a || null == b) {
throw new IllegalArgumentException("Variables cannot be null");
}
return a + b;
}
/**
* Method that performs some complicated Math Op
*
* @param a
* @param b
* @return
*/
public Integer complicatedMathOpBasedOnAddOp(Integer a, Integer b) {
return complicatedAddOp(offset, complicatedAddOp(a, b));
}
}
/**
* Initializes suite level stuff
*/
@BeforeSuite
public void initSuite() {
// This is one time operation
System.setProperty("addOffset", "10");
}
/**
* Init all test class level stuff
*/
@BeforeClass
public void init() {
businessClass = new BusinessClass(20);
}
/**
* This method tests if the business method
* {@link BusinessClass#complicatedAddOp(Integer, Integer)} throws an error
* when invoked with null in first argument
*/
@Test(expectedExceptions = { IllegalArgumentException.class }, groups = { "complicatedAddOp" })
public void compliAddOpWithErrorInFirstArgTest() {
// This method should throw an error
businessClass.complicatedAddOp(null, 23);
}
/**
* Tests if the method returns correct value and it only runs if the method
* compliAddOpWithErrorInSecondArgTest returns positive
*/
@Test(groups = { "complicatedAddOp" }, dependsOnMethods = "compliAddOpWithErrorInFirstArgTest")
public void myFirstCompliAddOpTest() {
// Invoke actual Business method and get the result
int actual = businessClass.complicatedAddOp(10, 23);
// Check if the returned by the actual is equal to what is expected
Assert.assertEquals(actual, 43);
}
/**
* This tests run only if all tests related to "complicatedAddOp" group are
* positive
*/
@Test(expectedExceptions = { IllegalArgumentException.class }, groups = "complicatedMathOp", dependsOnGroups = "complicatedAddOp")
public void complicatedMathOpWithErrorInFirstArg() {
// This method should throw an error
businessClass.complicatedMathOpBasedOnAddOp(null, 23);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment