This presentation describes the some of the major functionality of JUnit4 and TestNG .Each topic contains example so that a viewer can understand the usage and apply them in their code.
2. Why & What is Unit Testing
Testing is the process of checking the functionality of
the application whether it is working as per
requirements and to ensure that at developer
level, unit testing comes into picture. Unit testing is
the testing of single entity (class or method). Unit
testing is very essential to every software company to
give a quality product to their customers.
It ensures the delivery of right product with right
functionality.
8/13/2013 techniqpatch.blogspot.com 2
3. What is JUnit ?
JUnit is a Regression Testing Framework* for the Java
Programming Language. It is important in the test driven
development, and is one of a family of unit testing
frameworks collectively known as xUnit.
*One of the main reasons for regression testing is to
determine whether a change in one part of the software
affects other parts of the software
8/13/2013 techniqpatch.blogspot.com 3
4. How it works !!!
The idea is first testing then coding.
Test a little , code a little, test a little,
code a little ,……
8/13/2013 techniqpatch.blogspot.com 4
5. Features
JUnit is an open source framework
Provides Annotation to identify the test methods.
Provides Assertions for testing expected results.
Provides Test runners for running tests.
Simple and easy to write.
8/13/2013 techniqpatch.blogspot.com 5
6. What is Test case ??
A test case in software engineering is a set of
conditions or variables under which a tester will
determine whether an application or software system
is working properly or not.
A test case definition include the following
information :
pre-conditions
Set of input values
Set of expected results
How to execute the test and check results
Expected post-conditions.
8/13/2013 techniqpatch.blogspot.com 6
7. Test case in JUnit !!!
A Unit Test Case is a part of code which ensures that
the another part of code (method) works as expected.
A formal written unit test case is characterized by a
known input and by an expected output.
There must be at least two unit test cases for each
requirement: one positive test and one negative test.
8/13/2013 techniqpatch.blogspot.com 7
8. JUnit - Environment Setup
First setup jdk.
Set the environment variable JUNIT_HOME to
C:JUNIT .
Set the environment variable CLASSPATH to
%CLASSPATH%;%JUNIT_HOME%junit4.10.jar;.;
If you are using Eclipse , install the plug-in for JUnit.
8/13/2013 techniqpatch.blogspot.com 8
9. Component of JUnit
JUnit test framework provides following important
features/component
Fixtures
Test suites
Test runners
JUnit classes
8/13/2013 techniqpatch.blogspot.com 9
10. Fixtures
Fixtures is a fixed state of a set of objects used as a
baseline for running tests. The purpose of a test fixture
is to ensure that there is a well known and fixed
environment in which tests are run so that results are
repeatable. It includes
setUp() method which runs before every test
invocation.
tearDown() method which runs after every test
method.
8/13/2013 techniqpatch.blogspot.com 10
11. Fixture Example
import junit.framework.*;
public class JavaTest extends TestCase {
protected int value1, value2;
// assigning the values
protected void setUp(){
value1=2; value2=3;
}
// test method to add two values
@Test
public void testAdd(){
double result= value1 + value2;
assertTrue(result == 5);
}
protected void tearDown ()
{
//release resource
}
}
8/13/2013 techniqpatch.blogspot.com 11
12. Test Suite
Test suite means bundle a few unit test cases and run
it together. In JUnit, both @RunWith and
@Suite annotation are used to run the suite test.
8/13/2013 techniqpatch.blogspot.com 12
13. Test Suite Example
Suite test class Classes to be tested
import
org.junit.runner.RunWi
th;
import
org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestJunit1.class, TestJun
it2.class }) public class
JunitTestSuite {
}
import org.junit.Test;
import org.junit.Ignore;
import static
org.junit.Assert.assertEquals;
public class TestJunit1 {
String message = "Robert";
@Test
public void testPrintMessage() {
assertEquals(message,”hii”);
} }
//create another class as TestJunit2
8/13/2013 techniqpatch.blogspot.com 13
14. Test Runner
Test runner is used for executing the test cases.
Uses runClasses method of JUnitCore class of JUnit to
run test case of created test class.
Gets the result of test cases run in Result Object.
Gets failure(s) using getFailures() methods of Result
object.
Gets Success result using wasSuccessful() methods of
Result object.
8/13/2013 techniqpatch.blogspot.com 14
15. Example of Test Runner
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
} System.out.println(result.wasSuccessful());
}
}
8/13/2013 techniqpatch.blogspot.com 15
17. Assert
public class Assert extends java.lang.Object
This class provides a set of assertion methods useful for
writing tests. Only failed assertions are recorded. Some of
the important methods of Assert class are:
void assertEquals(boolean expected, boolean actual)
void assertFalse(boolean condition)
void assertNotNull(Object object)
void assertNull(Object object)
void assertTrue(boolean condition)
void fail()
void assertSame(boolean condition)
void assertNotSame(boolean condition)
8/13/2013 techniqpatch.blogspot.com 17
18. Assert Example
import org.junit.Test;
import static org.junit.Assert.*;
public class TestAssertions {
@Test
public void testAssertions() {
//test data
String str1 = new String (“sanjib");
String str2 = new String (“sanjib");
String str3 = null;
String str4 = "abc"; String str5 = "abc";
int val1 = 5; int val2 = 6;
String[] expectedArray = {"one", "two", "three"}; String[] resultArray = {"one", "two", "three"};
//Check that two objects are equal
assertEquals(str1, str2);
//Check that a condition is true
assertTrue (val1 < val2);
//Check that a condition is false
assertFalse(val1 > val2);
//Check that an object isn't null
assertNotNull(str1);
//Check that an object is null
assertNull(str3);
//Check if two object references point to the same object
assertSame(str4,str5);
//Check if two object references not point to the same object
assertNotSame(str1,str3);
//Check whether two arrays are equal to each other.
assertArrayEquals(expectedArray, resultArray); } }
8/13/2013 techniqpatch.blogspot.com 18
19. TestCase Class
public abstract class TestCase extends Assert implements Test
A test case defines the fixture to run multiple tests.Some important
method of this class are:
int countTestCases() //Counts the number of test cases
TestResult createResult()//Creates a default TestResult object.
String getName() //Gets the name of a TestCase.
TestResult run() //method to run thetest.
void run(TestResult result) //Runs the test case and collects the
results in TestResult.
void setName(String name)
void setUp()//e.g. open a network connection.
void tearDown() //e.g. close a network connection
8/13/2013 techniqpatch.blogspot.com 19
20. TestCase Example
package tv.seachange.ism.utils;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
public class TestCaseClass extends TestCase {
protected double val1,val2;
@Before
public void setUp() {
val1= 2.0;
val2= 3.0;
}
@Test
public void testAdd() {
System.out.println("No of Test Case = "+ this.countTestCases()); //count the number of test cases
String name= this.getName(); //test getName
System.out.println("Test Case Name = "+ name);
this.setName("newName"); //test setName
String newName= this.getName();
System.out.println("Updated Test Case Name = "+ newName);
assertFalse(val1>val2);
}
public void tearDown( ) {//tearDown used to close the connection or clean up activities
}
}
8/13/2013 techniqpatch.blogspot.com 20
21. Test Result
A TestResult collects the results of executing a test
case.Some of its methods are:
void addError(Test test, Throwable t)//Adds an error to the list of
errors.
void addFailure(Test test, AssertionFailedError t)//Adds a failure
to the list of failures.
int errorCount()//Gets the number of detected errors.
int failureCount()//Gets the number of detected failures.
void run(TestCase test)//Runs a TestCase.
void stop()//Marks that the test run should stop.
8/13/2013 techniqpatch.blogspot.com 21
22. TestSuite Class
A TestSuite is a Composite of Tests. It runs a collection
of test cases. Some of the methods are
void addTest(Test test)//Adds a test to the suite.
int countTestCases()//Counts the number of test cases that will be
run by this test.
String getName()//Returns the name of the suite.
void setName(String name)//Sets the name of the suite.
Test testAt(int index)//Returns the test at the given index.
8/13/2013 techniqpatch.blogspot.com 22
23. TestSuite Example
import junit.framework.*;
public class TestSuiteTest {
public static void main(String[] a) {
// add the test's in the suite
TestSuite suite = new
TestSuite(JunitTest1.class, JunitTest2.class, JunitTest3.class
);
TestResult result = new TestResult();
suite.run(result);
System.out.println("Number of test cases = " +
result.runCount());
} }
8/13/2013 techniqpatch.blogspot.com 23
24. Execution Flow
First of all beforeClass() method execute only once
Lastly, the afterClass() method executes only once.
before() method executes for each test case but before
executing the test case.
after() method executes for each test case but after the
execution of test case
In between before() and after() each test case executes.
8/13/2013 techniqpatch.blogspot.com 24
25. Execution Flow Example
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class JunitExecutionFlow {
//execute only once, in the starting
@BeforeClass public static void beforeClass() {
System.out.println("in before class");
}
//execute only once, in the end
@AfterClass public static void afterClass() {
System.out.println("in after class");
}
//execute for each test, before executing test
@Before public void before() {
System.out.println("in before");
}
//execute for each test, after executing test
@After public void after() {
System.out.println("in after");
}
//test case 1
@Test public void testCase1() {
System.out.println("in test case 1"); }
//test case 2
@Test public void testCase2() { System.out.println("in test case 2");
}
}
8/13/2013 techniqpatch.blogspot.com 25
26. Ignore Test
Sometimes it happens that our code is not ready and
test case written to test that method/code will fail if
run or we just don’t want to test that test case at that
moment. The @Ignore annotation helps in this
regards.
A test method annotated with @Ignore will not be
executed.
If a test class is annotated with @Ignore then all of its
test methods will be ignored.
8/13/2013 techniqpatch.blogspot.com 26
27. Ignored Test Example
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class IgnoreTest {
@Test
public void notIgnored()
{
System.out.println("this is executed");
}
@Ignore
@Test
public void itIsIgnored()
{
System.out.println("This test is ignored");
}
}
8/13/2013 techniqpatch.blogspot.com 27
28. Time test
Junit provides a handy option of Timeout. If a test case
takes more time than specified number of
milliseconds then Junit will automatically mark it as
failed. The timeout parameter is used along with
@Test annotation.
8/13/2013 techniqpatch.blogspot.com 28
29. Time Test xample
import org.junit.Test;
public class TimeTest {
@Test(timeout=10)
public void testTime()
{
for(int i=0;i<1000;i++){
System.out.println("hiiiiii");
}
}
}
8/13/2013 techniqpatch.blogspot.com 29
30. Exception Test
Junit provides a option of tracing the Exception
handling of code. You can test the code whether code
throws desired exception or not.
The expected parameter is used along with @Test
annotation.
8/13/2013 techniqpatch.blogspot.com 30
31. Exception Test Example
import org.junit.Test;
public class ExceptionTest {
@Test(expected=ArithmeticException.class)
public void exception()
{
int s=12/0;
}
}
8/13/2013 techniqpatch.blogspot.com 31
32. Parameterized Test
Junit 4 has introduced a new feature Parameterized
tests.Parameterized tests allow developer to run the same
test over and over again using different values. There are
five steps, that you need to follow to create Parameterized
tests.
Annotate test class with @RunWith(Parameterized.class)
Create a public static method annotated with @Parameters that returns
a Collection of Objects (as Array) as test data set.
Create a public constructor that takes in what is equivalent to one "row"
of test data.
Create an instance variable for each "column" of test data.
Create your tests case(s) using the instance variables as the source of
the test data.
8/13/2013 techniqpatch.blogspot.com 32
33. Parameterized Test Example
@RunWith(Parameterized.class)
public class ParameterizedTest {
private Integer inputNumber;
private Boolean expectedResult;
private OddEvenChecker oddEvenChecker;
@Before
public void initialize() {
oddEvenChecker = new OddEvenChecker();
}
public ParameterizedTest(Integer inputNumber,
Boolean expectedResult) {
this.inputNumber = inputNumber;
this.expectedResult = expectedResult;
}
@Parameterized.Parameters
public static Collection checkNumbers() {
return Arrays.asList(new Object[][] {
{ 2, true },{ 6, true },{ 19, false },{ 22, true },{ 23, false }
});
}
@Test
public void testOddEvenChecker() {
System.out.println("Parameterized Number is : " + inputNumber);
assertEquals(expectedResult,
oddEvenChecker.checkNumber(inputNumber));
}
}
8/13/2013 techniqpatch.blogspot.com 33
34. Are we done ??
Wow !! Now we know about Junit .But still some
question is there :
What if we want to test the dependency ? Or
What if we want to use Object as parameter not only
primitives ??
8/13/2013 techniqpatch.blogspot.com 34
35. Yes we can !!
And the solution is TESTNG
8/13/2013 techniqpatch.blogspot.com 35
36. TestNG
It stands for NEXT GENERATION JAVA TESTING.
TestNG is a testing framework inspired
from JUnit and NUnit but introducing some new
functionalities in order to make it more powerful and
easier to use.
8/13/2013 techniqpatch.blogspot.com 36
37. Features of TestNG
Annotations.
Run your tests in arbitrarily big thread pools with various
policies available (all methods in their own thread, one
thread per test class, etc...).
Flexible test configuration.
Support for data-driven testing (with @DataProvider).
Support for parameters.
Powerful execution model (no more TestSuite).
Supported by a variety of tools and plug-ins
(Eclipse, IDEA, Maven, etc...).
Dependent methods for application server testing.
8/13/2013 techniqpatch.blogspot.com 37
38. Annotations
import java.util.*;
import org.testng.Assert;
import org.testng.annotations.*;
public class TestNGTest1 {
private Collection collection;
@BeforeClass
public void oneTimeSetUp()
{ // one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp"); }
@AfterClass
public void oneTimeTearDown() {
// one-time cleanup code
System.out.println("@AfterClass - oneTimeTearDown"); }
@BeforeMethod
public void setUp() {
collection = new ArrayList();
System.out.println("@BeforeMethod - setUp"); }
@AfterMethod
public void tearDown() {
collection.clear();
System.out.println("@AfterMethod - tearDown"); }
@Test
public void testEmptyCollection() {
Assert.assertEquals(collection.isEmpty(),true);
System.out.println("@Test - testEmptyCollection"); }
@Test
public void testOneItemCollection() {
collection.add("itemA");
Assert.assertEquals(collection.size(),1);
System.out.println("@Test - testOneItemCollection");
} }
The annotations are :
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
@Test
@BeforeTest
@AfterTest etc..
8/13/2013 techniqpatch.blogspot.com 38
39. Expected Exception Test
import org.testng.annotations.*;
public class TestNGTest2 {
@Test(expectedExceptions = ArithmeticException.class)
public void divisionWithException()
{
int i = 1/0;
}
}
8/13/2013 techniqpatch.blogspot.com 39
40. Ignore and Time test
In TestNG for ignoring a test below mention
annotation is used : @Test(enabled=false)
For Time test the annotation is same as Junit.
@Test(timeOut = 1000)
8/13/2013 techniqpatch.blogspot.com 40
41. Suite or Grouping
The grouping is used for running multiple test as a
group of tests. Unlike JUnit in TestNG we can make
different group of test method and can run single or
multiple group.
8/13/2013 techniqpatch.blogspot.com 41
42. Suite or Grouping Test
public class GroupingTest {
@Test(groups="group1")
public void testingGroup1 () {
System.out.println("Method - testingMethod1()"); }
@Test(groups="group2")
public void testingGroup2 () {
System.out.println("Method -
testingMethod2()"); }
@Test(groups="group1")
public void testingGroup1_1 () {
System.out.println("Method - testingMethod1_1()");
}
@Test(groups="group3")
public void testingGroup4() {
System.out.println("Method - testingMethod4()");
} }
8/13/2013 techniqpatch.blogspot.com 42
<?xml version="1.0"
encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM
"http://testng.org/testng-1.0.dtd"
>
<suite name="My suite">
<test name="testinggroup">
<groups>
<run>
<include name="group1"/>
</run>
</groups>
<classes>
<class name="GroupingTest"
/>
</classes>
</test>
</suite>
43. TestNG’s Parameterized Test
TestNG’s Parameterized test is very user friendly and
flexible (either in XML file or inside the class). It can
support many complex data type as parameter value
and the possibility is unlimited. Moreover we even can
pass in our own object for Parameterized test.
8/13/2013 techniqpatch.blogspot.com 43
44. TestNG Parameterized Example
public class ParameterizedTest {
@Test(dataProvider =
"parameterizedDataProvider")
public void testParameter(User user,boolean
flag) {
System.out.println("the user name is
:"+user.getName());
System.out.println("the user id is
:"+user.getId());
}
@DataProvider(name="parameterizedDataProvi
der")
public Object[][] parameterizedDataProvider() {
return new Object[][] {
{new User("Sanjib",1),true},
{new User("Dhar",2),false}
}; }
}
class User{
private String name;
private int id;
public User() {
}
public User(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
8/13/2013 techniqpatch.blogspot.com 44
45. Dependency Test
The TestNG has a feature called The “Dependency
Test”, means methods are tested base on dependency.
If the dependent method fails, all the subsequent test
methods will be skipped, not marked as failed.
8/13/2013 techniqpatch.blogspot.com 45
46. @DataProvider
A Data Provider is a method annotated with
@DataProvider. This annotation has only one string
attribute: its name. If the name is not
supplied, theData Provider’s name automatically
defaults to the method’s name.
A Data Provider returns Java objects that will be
passed as parameters to an @Test method. The name
of the Data Provider to receive parameters from is
specified in the dataProvider attribute of the @Test
annotation.
8/13/2013 techniqpatch.blogspot.com 46
47. Dependency Test example
public class DependencyTest {
@Test
public void test1() {
Object object = null;
System.out.println("This is test1");
Assert.assertNotNull(object);
}
@Test(dependsOnMethods={“test1"})
public void test2() {
System.out.println("This is test2");
}
@Test
public void test3() {
System.out.println("This is test3");
}
}
8/13/2013 techniqpatch.blogspot.com 47