Junit Tutorial
Junit Tutorial
JUNIT TUTORIAL
Simply Easy Learning by tutorialspoint.com
tutorialspoint.com
i
ABOUT THE TUTORIAL
JUnit Tutorial
JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-
driven development, and is one of a family of unit testing frameworks collectively known as xUnit that originated with JUnit.
This tutorial will teach you how to use JUnit in your day-2-day life of any project unit testing while working with Java
programming language.
Audience
This tutorial has been prepared for the beginners to help them understand basic functionality of JUnit tool. After completing
this tutorial you will find yourself at a moderate level of expertise in using JUnit testing framework from where you can take
yourself to next levels.
Prerequisites
We assume you are going to use JUnit to handle all levels of Java projects development. So it will be good if you have
knowledge of software development using any programming language specially Java programming and software testing
process.
This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of
the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial
content contains some errors, please contact us at webmaster@tutorialspoint.com
ii
Table of Contents
JUnit Tutorial ............................................................................. i
Audience ................................................................................... i
Prerequisites ............................................................................. i
Copyright & Disclaimer Notice ................................................... i
JUnit Overview ...........................................................................
What is JUnit ? ...............................................................................................
Features ........................................................................................................
What is a Unit Test Case ? ...............................................................................
JUnit Environment Setup............................................................
System Requirement ......................................................................................
Step 1 - verify Java installation in your machine.................................................
Step 2: Set JAVA environment .........................................................................
Step 3: Download Junit archive ........................................................................
Step 4: Set JUnit environment .........................................................................
Step 5: Set CLASSPATH variable .......................................................................
Step 6: Test JUnit Setup ..................................................................................
Step 7: Verify the Result ..................................................................................
JUnit Test Framework ................................................................
Features ........................................................................................................
Fixtures .........................................................................................................
Test suite.......................................................................................................
Test runner ....................................................................................................
JUnit classes ..................................................................................................
JUnit Basic Usage ......................................................................
Create a Class ................................................................................................
Create Test Case Class ....................................................................................
Create Test Runner Class.................................................................................
JUnit API ....................................................................................
Assert Class ...................................................................................................
TestCase Class ................................................................................................
TestResult Class .............................................................................................
TestSuite Class ...............................................................................................
iii
JUnit Writing Tests .....................................................................
JUnit Using Assertion .................................................................
Annotation ....................................................................................................
JUnit Execution Procedure .........................................................
JUnit Executing Tests.................................................................
Create a Class ................................................................................................
Create Test Case Class ....................................................................................
Create Test Runner Class.................................................................................
JUnit Test Suite ..........................................................................
Create a Class ................................................................................................
Create Test Case Classes .................................................................................
Create Test Suite Class ....................................................................................
Create Test Runner Class.................................................................................
JUnit Ignore Test ........................................................................
Create a Class ................................................................................................
Create Test Case Class ....................................................................................
Create Test Runner Class.................................................................................
JUnit Time Test ..........................................................................
Create a Class ................................................................................................
Create Test Case Class ....................................................................................
Create Test Runner Class.................................................................................
JUnit Exception Test ..................................................................
Create a Class ................................................................................................
Create Test Case Class ....................................................................................
Create Test Runner Class.................................................................................
JUnit Parameterized Test ...........................................................
Create a Class ................................................................................................
Create Parameterized Test Case Class ..............................................................
Create Test Runner Class.................................................................................
JUnit Plug with ANT ...................................................................
Step 1: Download Apache Ant .........................................................................
Step 2: Set Ant Environment............................................................................
Step 3: Download Junit Archive .......................................................................
Step 4: Create Project Structure .......................................................................
Create ANT Build.xml ......................................................................................
JUnit Plug with Eclipse ...............................................................
Step 1: Download Junit archive ........................................................................
Step 2: Set Eclipse environment .......................................................................
Step 3: Verify Junit installation in Eclipse ..........................................................
iii
JUnit Extensions ........................................................................
Cactus ...........................................................................................................
JWebUnit ......................................................................................................
XMLUnit ........................................................................................................
MockObject ...................................................................................................
iii
1
CHAPTER
JUnit Overview
T esting 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.
Executing the test cases manually without any Taking tool support and executing the test
tool support is known as manual testing. cases by using automation tool is known as
automation testing.
Time consuming and tedious: Since test cases
Fast Automation runs test cases significantly
are executed by human resources so it is very
slow and tedious. faster than human resources.
Less reliable: Manual testing is less reliable as More reliable: Automation tests perform
tests may not be performed with precision each precisely same operation each time they are
time because of human errors. run.
What is JUnit ?
JUnit is a unit 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.
TUTORIALS POINT
Simply Easy Learning
JUnit promotes the idea of "first testing then coding", which emphasis on setting up the test data for
a piece of code which can be tested first and then can be implemented. This approach is like "test a
little, code a little, test a little, code a little..." which increases programmer productivity and stability
of program code that reduces programmer stress and the time spent on debugging.
Features
JUnit is an open source framework which is used for writing & running tests.
JUnit tests allow you to write code faster which increasing quality
JUnit tests can be run automatically and they check their own results and provide
immediate feedback. There's no need to manually comb through a report of test results.
JUnit tests can be organized into test suites containing test cases and even other test
suites.
Junit shows test progress in a bar that is green if test is going fine and it turns red when a
test fails.
A formal written test-case is characterized by a known input and by an expected output, which is
worked out before the test is executed. The known input should test a precondition and the
expected output should test a post condition.
There must be at least two test cases for each requirement: one positive test and one negative test.
If a requirement has sub-requirements, each sub-requirement must have at least two test cases as
positive and negative.
TUTORIALS POINT
Simply Easy Learning
2
CHAPTER
J
machine.
Unit is a framework for Java, so the very first requirement is to have JDK installed in your
System Requirement
JDK 1.5 or above.
OS Task Command
OS Output
java version "1.6.0_21"
Windows Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
TUTORIALS POINT
Simply Easy Learning
sharing)
If you do not have Java installed, install the Java Software Development Kit (SDK)
fromhttp://www.oracle.com/technetwork/java/javase/downloads/index.html. We are assuming
Java 1.6.0_21 as installed version for this tutorial.
OS Output
Set the environment variable JAVA_HOME to C:\Program
Windows
Files\Java\jdk1.6.0_21
OS Output
Append the string ;C:\Program Files\Java\jdk1.6.0_21\bin to the
Windows
end of the system variable, Path.
OS Archive name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar
OS Output
TUTORIALS POINT
Simply Easy Learning
Step 5: Set CLASSPATH variable
Set the CLASSPATH environment variable to point to the JUNIT jar location. Assuming, we've
stored junit4.10.jar in JUNIT folder on various Operating Systems as follows.
OS Output
Set the environment variable CLASSPATH to
Windows
%CLASSPATH%;%JUNIT_HOME%\junit4.10.jar;.;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
@Test
public void testAdd() {
String str= "Junit is working fine";
assertEquals("Junit is working fine",str);
}
}
Create a java class file name TestRunner in C:\ > JUNIT_WORKSPACE to execute Test
case(s)
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());
}
}
C:\JUNIT_WORKSPACE>java TestRunner
true
TUTORIALS POINT
Simply Easy Learning
3
CHAPTER
Java and accelerate programming speed and increase the quality of code. JUnit Framework can be
easily integrated with either of the followings:
Eclipse
Ant
Maven
Features
JUnit test framework provides following important features
Fixtures
Test suites
Test runners
JUnit classes
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
import junit.framework.*;
TUTORIALS POINT
Simply Easy Learning
public class JavaTest extends TestCase {
protected int value1, value2;
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. Here is an example which uses TestJunit1 &
TestJunit2 test classes.
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
assertEquals(message, messageUtil.printMessage());
}
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
TUTORIALS POINT
Simply Easy Learning
Test runner
Test runner is used for executing the test cases. Here is an example which assumes TestJunit test
class already exists.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
JUnit classes
JUnit classes are important classes which is used in writing and testing JUnits. Some of the
important classes are
TestCase which contain a test case defines the fixture to run multiple tests.
TestResult which contain methods to collect the results of executing a test case.
TUTORIALS POINT
Simply Easy Learning
4
CHAPTER
N
example.
ow we'll show you a step by step process to get a kick start in JUnit using a basic
Create a Class
Create a java class to be tested say MessageUtil.java in C:\ > JUNIT_WORKSPACE
/*
* This class prints the given message on console.
*/
public class MessageUtil {
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
Implement the test condition and check the condition using assertEquals API of Junit.
TUTORIALS POINT
Simply Easy Learning
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
Use runClasses method of JUnitCore class of JUnit to run test case of above created test
class
Create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to execute Test
case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the MessageUtil, Test case and Test Runner classes using javac
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Hello World
true
TUTORIALS POINT
Simply Easy Learning
Now update TestJunit in C:\ > JUNIT_WORKSPACE so that test fails. Change the message string.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
@Test
public void testPrintMessage() {
message = "New Word";
assertEquals(message,messageUtil.printMessage());
}
}
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Hello World
testPrintMessage(TestJunit): expected:<[New Wor]d> but was:<[Hello Worl]d>
false
TUTORIALS POINT
Simply Easy Learning
5
CHAPTER
JUnit API
T he most important package in JUnit is junit.framework which contain all the core
Assert Class
Following is the declaration for org.junit.Assert class:
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:
6 void fail()
TUTORIALS POINT
Simply Easy Learning
Fails a test with no message.
Let's try to cover few of the above mentioned methods in an example. Create a java class file name
TestJunit1.java in C:\ > JUNIT_WORKSPACE
import org.junit.Test;
import static org.junit.Assert.*;
public class TestJunit1 {
@Test
public void testAdd() {
//test data
int num= 5;
String temp= null;
String str= "Junit is working fine";
Next, let's create a java class file name TestRunner1.java in C:\ > JUNIT_WORKSPACE to
execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the Test case and Test Runner classes using javac
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner1
true
TestCase Class
Following is the declaration for org.junit.TestCaset class:
TUTORIALS POINT
Simply Easy Learning
public abstract class TestCase extends Assert implements Test
A test case defines the fixture to run multiple tests. Some of the important methods
of TestCase class are
int countTestCases()
1
Counts the number of test cases executed by run(TestResult result).
TestResult createResult()
2
Creates a default TestResult object.
String getName()
3
Gets the name of a TestCase.
TestResult run()
4
A convenience method to run this test, collecting the results with a default TestResult object.
void setUp()
7
Sets up the fixture, for example, open a network connection.
void tearDown()
8
Tears down the fixture, for example, close a network connection.
String toString()
9
Returns a string representation of the test case.
Let's try to cover few of the above mentioned methods in an example. Create a java class file name
TestJunit2.java in C:\ > JUNIT_WORKSPACE
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
public class TestJunit2 extends TestCase {
protected double fValue1;
protected double fValue2;
@Before
public void setUp() {
fValue1= 2.0;
fValue2= 3.0;
}
@Test
public void testAdd() {
//test getName
String name= this.getName();
System.out.println("Test Case Name = "+ name);
//test setName
TUTORIALS POINT
Simply Easy Learning
this.setName("testNewAdd");
String newName= this.getName();
System.out.println("Updated Test Case Name = "+ newName);
}
//tearDown used to close the connection or clean up activities
public void tearDown( ) {
}
}
Next, let's create a java class file name TestRunner2.java in C:\ > JUNIT_WORKSPACE to
execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the Test case and Test Runner classes using javac
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner2
No of Test Case = 1
Test Case Name = testAdd
Updated Test Case Name = testNewAdd
true
TestResult Class
Following is the declaration for org.junit.TestResult class:
A TestResult collects the results of executing a test case. It is an instance of the Collecting
Parameter pattern. The test framework distinguishes between failures and errors. A failure is
anticipated and checked for with assertions. Errors are unanticipated problems like an
ArrayIndexOutOfBoundsException. Some of the important methods of TestResult class are:
TUTORIALS POINT
Simply Easy Learning
void addFailure(Test test, AssertionFailedError t)
2
Adds a failure to the list of failures.
int errorCount()
4
Gets the number of detected errors.
Enumeration<TestFailure> errors()
5
Returns an Enumeration for the errors.
int failureCount()
6
Gets the number of detected failures.
void stop()
10
Marks that the test run should stop.
import org.junit.Test;
import junit.framework.AssertionFailedError;
import junit.framework.TestResult;
Next, let's create a java class file name TestRunner3.java in C:\ > JUNIT_WORKSPACE to
execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
TUTORIALS POINT
Simply Easy Learning
Result result = JUnitCore.runClasses(TestJunit3.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner3
true
TestSuite Class
Following is the declaration for org.junit.TestSuite class:
A TestSuite is a Composite of Tests. It runs a collection of test cases. Some of the important
methods of TestSuite class are
int countTestCases()
3
Counts the number of test cases that will be run by this test.
String getName()
4
Returns the name of the suite.
int testCount()
8
Returns the number of tests in this suite.
TUTORIALS POINT
Simply Easy Learning
static Test warning(String message)
9
Returns a test which will fail and log a warning message.
Create a java class file name JunitTestSuite.java in C:\ > JUNIT_WORKSPACE to create Test
suite
import junit.framework.*;
public class JunitTestSuite {
public static void main(String[] a) {
// add the test's in the suite
TestSuite suite = new TestSuite(TestJunit1.class,
TestJunit2.class, TestJunit3.class );
TestResult result = new TestResult();
suite.run(result);
System.out.println("Number of test cases = " + result.runCount());
}
}
C:\JUNIT_WORKSPACE>javac JunitTestSuite.java
C:\JUNIT_WORKSPACE>java JunitTestSuite
No of Test Case = 1
Test Case Name = testAdd
Updated Test Case Name = testNewAdd
Number of test cases = 3
TUTORIALS POINT
Simply Easy Learning
6
CHAPTER
H ere we will see one complete example of JUnit testing using POJO class, Business logic
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the monthlySalary
*/
public double getMonthlySalary() {
return monthlySalary;
}
/**
* @param monthlySalary the monthlySalary to set
*/
public void setMonthlySalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
TUTORIALS POINT
Simply Easy Learning
this.age = age;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
TUTORIALS POINT
Simply Easy Learning
@Test
public void testCalculateYearlySalary() {
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
double salary= empBusinessLogic.calculateYearlySalary(employee);
assertEquals(96000, salary, 0.0);
}
}
Next, let's create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to
execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the Test case and Test Runner classes using javac
C:\JUNIT_WORKSPACE>javac EmployeeDetails.java
EmpBusinessLogic.java TestEmployeeDetails.java TestRunner.java
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
true
TUTORIALS POINT
Simply Easy Learning
7
CHAPTER
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:
Let's try to cover all of the above mentioned methods in an example. Create a java class file name
TestAssertions.java in C:\ > JUNIT_WORKSPACE
import org.junit.Test;
import static org.junit.Assert.*;
TUTORIALS POINT
Simply Easy Learning
@Test
public void testAssertions() {
//test data
String str1 = new String ("abc");
String str2 = new String ("abc");
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"};
Next, let's create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to
execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the Test case and Test Runner classes using javac
Now run the Test Runner which will run test case defined in provided Test Case class.
TUTORIALS POINT
Simply Easy Learning
C:\JUNIT_WORKSPACE>java TestRunner
true
Annotation
Annotations are like meta-tags that you can add to you code and apply them to methods or in
class. These annotation in JUnit gives us information about test methods , which methods are
going to run before & after test methods, which methods run before & after all the methods, which
methods or class will be ignore during execution. List of annotations and their meaning in JUnit :
@Test
1 The Test annotation tells JUnit that the public void method to which it is attached can be run
as a test case.
@Before
2 Several tests need similar objects created before they can run. Annotating a public void
method with @Before causes that method to be run before each Test method.
@After
If you allocate external resources in a Before method you need to release them after the test
3
runs. Annotating a public void method with @After causes that method to be run after the
Test method.
@BeforeClass
4 Annotating a public static void method with @BeforeClass causes it to be run once before
any of the test methods in the class.
@AfterClass
5 This will perform the method after all tests have finished. This can be used to perform clean-
up activities.
@Ignore
6
The Ignore annotation is used to ignore the test and that test will not be executed.
Create a java class file name JunitAnnotation.java in C:\ > JUNIT_WORKSPACE to test annotation
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
TUTORIALS POINT
Simply Easy Learning
}
Next, let's create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to
execute annotations
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the Test case and Test Runner classes using javac
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
in before class
in before
in test
in after
in after class
true
TUTORIALS POINT
Simply Easy Learning
8
CHAPTER
T his tutorial explains the execution procedure of methods in JUnit which means that which
method is called first and which one after that. Here is the execution procedure of the JUint test API
methods with the example.
Create a java class file name JunitAnnotation.java in C:\ > JUNIT_WORKSPACE to test annotation
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
//test case 1
@Test
public void testCase1() {
System.out.println("in test case 1");
}
TUTORIALS POINT
Simply Easy Learning
//test case 2
@Test
public void testCase2() {
System.out.println("in test case 2");
}
}
Next, let's create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to
execute annotations
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the Test case and Test Runner classes using javac
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
in before class
in before
in test case 1
in after
in before
in test case 2
in after
in after class
See the above output and this is how the JUnit execution procedure is.
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
TUTORIALS POINT
Simply Easy Learning
9
CHAPTER
T he test cases are executed using JUnitCore class. JUnitCore is a facade for running tests.
It supports running JUnit 4 tests, JUnit 3.8.x tests, and mixtures. To run tests from the command
line, run java org.junit.runner.JUnitCore <TestClass>. For one-shot test runs, use the static method
runClasses(Class[]).
Here we will see how can we execute the tests with the help of JUnitCore.
Create a Class
Create a java class to be tested say MessageUtil.java in C:\ > JUNIT_WORKSPACE
/*
* This class prints the given message on console.
*/
public class MessageUtil {
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
TUTORIALS POINT
Simply Easy Learning
Add a test method testPrintMessage() to your test class.
Implement the test condition and check the condition using assertEquals API of Junit.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the Test case and Test Runner classes using javac
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Hello World
true
TUTORIALS POINT
Simply Easy Learning
CHAPTER
10
JUnit Test Suite
T est 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. This tutorial will show you an
example having two TestJunit1 & TestJunit2 test classes to run together using Test Suite.
Create a Class
Create a java class to be tested say MessageUtil.java in C:\ > JUNIT_WORKSPACE
/*
* This class prints the given message on console.
*/
public class MessageUtil {
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
TUTORIALS POINT
Simply Easy Learning
String message = "Robert";
MessageUtil messageUtil = new MessageUtil(message);
@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
assertEquals(message, messageUtil.printMessage());
}
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
Create a java class file name TestSuite.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestJunit1.class,
TestJunit2.class
})
public class JunitTestSuite {
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
TUTORIALS POINT
Simply Easy Learning
public static void main(String[] args) {
Result result = JUnitCore.runClasses(JunitTestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Inside testPrintMessage()
Robert
Inside testSalutationMessage()
Hi Robert
true
TUTORIALS POINT
Simply Easy Learning
CHAPTER
11
JUnit Ignore Test
S ometimes it happens that our code is not ready and test case written to test that
method/code will fail if run. The @Ignore annotation helps in this regards.
If a test class is annotated with @Ignore then none of its test methods will be executed.
Create a Class
Create a java class to be tested say MessageUtil.java in C:\ > JUNIT_WORKSPACE
/*
* This class prints the given message on console.
*/
public class MessageUtil {
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
TUTORIALS POINT
Simply Easy Learning
Create Test Case Class
Create a java test class say TestJunit.java.
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
@Ignore
@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
message = "Robert";
assertEquals(message,messageUtil.printMessage());
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the MessageUtil, Test case and Test Runner classes using javac
Now run the Test Runner which will not run testPrintMessage() test case defined in provided Test
Case class.
TUTORIALS POINT
Simply Easy Learning
C:\JUNIT_WORKSPACE>java TestRunner
Inside testSalutationMessage()
Hi!Robert
true
Now update TestJunit in C:\ > JUNIT_WORKSPACE to ignore all test cases. Add @Ignore at class
level
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
@Ignore
public class TestJunit {
@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
message = "Robert";
assertEquals(message,messageUtil.printMessage());
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
C:\JUNIT_WORKSPACE>javac TestJunit.java
Now run the Test Runner which will not run any test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
true
TUTORIALS POINT
Simply Easy Learning
CHAPTER
12
JUnit Time Test
J unit 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. Now let's see @Test(timeout) in action.
Create a Class
Create a java class to be tested say MessageUtil.java in C:\ > JUNIT_WORKSPACE.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
TUTORIALS POINT
Simply Easy Learning
Add timeout of 1000 to testPrintMessage() test case.
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
@Test(timeout=1000)
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
messageUtil.printMessage();
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the MessageUtil, Test case and Test Runner classes using javac
Now run the Test Runner which will run test cases defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output. testPrintMessage() test case will mark unit testing failed.
Inside testPrintMessage()
Robert
Inside testSalutationMessage()
Hi!Robert
TUTORIALS POINT
Simply Easy Learning
testPrintMessage(TestJunit): test timed out after 1000 milliseconds
false
TUTORIALS POINT
Simply Easy Learning
CHAPTER
13
JUnit Exception Test
J unit 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. Now let's see @Test(expected) in action.
Create a Class
Create a java class to be tested say MessageUtil.java in C:\ > JUNIT_WORKSPACE.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
TUTORIALS POINT
Simply Easy Learning
Add expected exception ArithmeticException to testPrintMessage() test case.
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
@Test(expected = ArithmeticException.class)
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
messageUtil.printMessage();
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
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());
}
}
Compile the MessageUtil, Test case and Test Runner classes using javac
Now run the Test Runner which will run test cases defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Inside testPrintMessage()
Robert
Inside testSalutationMessage()
Hi!Robert
true
TUTORIALS POINT
Simply Easy Learning
CHAPTER
14
JUnit Parameterized Test
J Unit 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.
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 your tests case(s) using the instance variables as the source of the test data.
The test case will be invoked once per each row of data. Let's see Parameterized tests in action.
Create a Class
Create a java class to be tested say PrimeNumberChecker.java in C:\ >
JUNIT_WORKSPACE.
TUTORIALS POINT
Simply Easy Learning
Create a java class file name PrimeNumberCheckerTest.java in C:\ > JUNIT_WORKSPACE
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.Before;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class PrimeNumberCheckerTest {
private Integer inputNumber;
private Boolean expectedResult;
private PrimeNumberChecker primeNumberChecker;
@Before
public void initialize() {
primeNumberChecker = new PrimeNumberChecker();
}
@Parameterized.Parameters
public static Collection primeNumbers() {
return Arrays.asList(new Object[][] {
{ 2, true },
{ 6, false },
{ 19, true },
{ 22, false },
{ 23, true }
});
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
TUTORIALS POINT
Simply Easy Learning
System.out.println(result.wasSuccessful());
}
}
Now run the Test Runner which will run test cases defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Parameterized Number is : 2
Parameterized Number is : 6
Parameterized Number is : 19
Parameterized Number is : 22
Parameterized Number is : 23
true
TUTORIALS POINT
Simply Easy Learning
CHAPTER
15
JUnit Plug with ANT
I
steps:
n this example, we will demonstrate how to run JUnit using ANT. Let's follow the given
OS Archive name
Windows apache-ant-1.8.4-bin.zip
Linux apache-ant-1.8.4-bin.tar.gz
Mac apache-ant-1.8.4-bin.tar.gz
OS Output
Append Ant compiler location to System Path is as follows for different OS:
OS Output
Windows Append the string ;%ANT_HOME\bin to the end of the system variable, Path.
TUTORIALS POINT
Simply Easy Learning
Step 3: Download Junit Archive
Download JUnit Archive
OS Archive name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar
/*
* This class prints the given message on console.
*/
public class MessageUtil {
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
TUTORIALS POINT
Simply Easy Learning
public class TestMessageUtil {
@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
assertEquals(message,messageUtil.printMessage());
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
Copy junit-4.10.jar in C:\ > JUNIT_WORKSPACE > TestJunitWithAnt > lib folder
C:\JUNIT_WORKSPACE\TestJunitWithAnt>ant
TUTORIALS POINT
Simply Easy Learning
Buildfile: C:\JUNIT_WORKSPACE\TestJunitWithAnt\build.xml
clean:
compile:
[javac] Compiling 2 source files to C:\JUNIT_WORKSPACE\TestJunitWithAnt\test
[javac] [parsing started C:\JUNIT_WORKSPACE\TestJunitWithAnt\src\
MessageUtil.java]
[javac] [parsing completed 18ms]
[javac] [parsing started C:\JUNIT_WORKSPACE\TestJunitWithAnt\src\
TestMessageUtil.java]
[javac] [parsing completed 2ms]
[javac] [search path for source files: C:\JUNIT_WORKSPACE\
TestJunitWithAnt\src]
[javac] [loading java\lang\Object.class(java\lang:Object.class)]
[javac] [loading java\lang\String.class(java\lang:String.class)]
[javac] [loading org\junit\Test.class(org\junit:Test.class)]
[javac] [loading org\junit\Ignore.class(org\junit:Ignore.class)]
[javac] [loading org\junit\Assert.class(org\junit:Assert.class)]
[javac] [loading java\lang\annotation\Retention.class
(java\lang\annotation:Retention.class)]
[javac] [loading java\lang\annotation\RetentionPolicy.class
(java\lang\annotation:RetentionPolicy.class)]
[javac] [loading java\lang\annotation\Target.class
(java\lang\annotation:Target.class)]
[javac] [loading java\lang\annotation\ElementType.class
(java\lang\annotation:ElementType.class)]
[javac] [loading java\lang\annotation\Annotation.class
(java\lang\annotation:Annotation.class)]
[javac] [checking MessageUtil]
[javac] [loading java\lang\System.class(java\lang:System.class)]
[javac] [loading java\io\PrintStream.class(java\io:PrintStream.class)]
[javac] [loading java\io\FilterOutputStream.class
(java\io:FilterOutputStream.class)]
[javac] [loading java\io\OutputStream.class(java\io:OutputStream.class)]
[javac] [loading java\lang\StringBuilder.class
(java\lang:StringBuilder.class)]
[javac] [loading java\lang\AbstractStringBuilder.class
(java\lang:AbstractStringBuilder.class)]
[javac] [loading java\lang\CharSequence.class(java\lang:CharSequence.class)]
[javac] [loading java\io\Serializable.class(java\io:Serializable.class)]
[javac] [loading java\lang\Comparable.class(java\lang:Comparable.class)]
[javac] [loading java\lang\StringBuffer.class(java\lang:StringBuffer.class)]
[javac] [wrote C:\JUNIT_WORKSPACE\TestJunitWithAnt\test\MessageUtil.class]
[javac] [checking TestMessageUtil]
[javac] [wrote
C:\JUNIT_WORKSPACE\TestJunitWithAnt\test\TestMessageUtil.class]
[javac] [total 281ms]
test:
[junit] Testsuite: TestMessageUtil
[junit] Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 0.008 sec
[junit]
[junit] ------------- Standard Output ---------------
[junit] Inside testPrintMessage()
[junit] Robert
[junit] Inside testSalutationMessage()
[junit] Hi!Robert
[junit] ------------- ---------------- ---------------
BUILD SUCCESSFUL
Total time: 0 seconds
TUTORIALS POINT
Simply Easy Learning
CHAPTER
16
JUnit Plug with Eclipse
OS Archive name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar
TUTORIALS POINT
Simply Easy Learning
We assume that your eclipse has inbuilt Junit plugin if it is not available in
C:\>eclipse/plugins directory, then you can download it from JUnit Plugin. Unzip the
downloaded zip file in the plugin folder of the eclipse. Finally restart eclipse.
Now your eclipse is ready for the development of JUnit test cases.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
TUTORIALS POINT
Simply Easy Learning
return message;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
Finally, verify the output of the program by right click on program and run as junit
TUTORIALS POINT
Simply Easy Learning
Verify the result
TUTORIALS POINT
Simply Easy Learning
CHAPTER
17
JUnit Extensions
Cactus
JWebUnit
XMLUnit
MockObject
Cactus
Cactus is a simple test framework for unit testing server-side java code (Servlets, EJBs, Tag Libs,
Filters). The intent of Cactus is to lower the cost of writing tests for server-side code. It uses JUnit
and extends it. Cactus implements an in-container strategy, meaning that tests are executed
inside the container.
The Cactus Framework: This is the heart of Cactus. It is the engine that provides the API
to write Cactus tests.
The Cactus Integration Modules: They are front ends and frameworks that provide easy
ways of using the Cactus Framework (Ant scripts, Eclipse plugin, Maven plugin).
The Cactus Samples: They are simple projects that demonstrate how to write Cactus
tests and how to use some of the Integration Modules.
JWebUnit
JWebUnit is a Java-based testing framework for web applications. It wraps existing testing
frameworks such as HtmlUnit and Selenium with a unified, simple testing interface to allow you to
quickly test the correctness of your web applications.
TUTORIALS POINT
Simply Easy Learning
JWebUnit provides a high-level Java API for navigating a web application combined with a set of
assertions to verify the application's correctness. This includes navigation via links, form entry and
submission, validation of table contents, and other typical business web application features.
The simple navigation methods and ready-to-use assertions allow for more rapid test creation
than using only JUnit or HtmlUnit. And if you want to switch from HtmlUnit to other plugins such as
Selenium (available soon), there is no need to rewrite your tests.
XMLUnit
XMLUnit provides classes to validate or compare XML files or to assert the value of XPath
expressions applied to them. XMLUnit for Java provides integration with JUnit while XMLUNit for
.NET integrates with NUnit to simplify unit testing code that generates XML.
MockObject
In a unit test, mock objects can simulate the behavior of complex, real (non-mock) objects and are
therefore useful when a real object is impractical or impossible to incorporate into a unit test. The
common coding style for testing with mock objects is to:
TUTORIALS POINT
Simply Easy Learning