JUnit Lab Manual - Quick Guide
JUnit Lab Manual - Quick Guide
JUnit - Overview
Testing is the process of checking the functionality of an application to ensure it runs as per
requirements. Unit testing comes into picture at the developers’ level; it is the testing of single
entity (class or method). Unit testing plays a critical role in helping a software company deliver
quality products to its customers.
Unit testing can be done in two ways − manual testing and automated testing.
Executing a test cases manually without any Taking tool support and executing the test cases by
tool support is known as manual testing. using an automation tool is known as automation
testing.
Time-consuming and tedious − Since test Fast − Automation runs test cases significantly
cases are executed by human resources, it is faster than human resources.
very slow and tedious.
Less reliable − Manual testing is less More reliable − Automation tests are precise and
reliable, as it has to account for human reliable.
errors.
What is JUnit ?
JUnit is a unit testing framework for Java programming language. It plays a crucial role test-
driven development, and is a family of unit testing frameworks collectively known as xUnit.
JUnit promotes the idea of "first testing then coding", which emphasizes on setting up the test
data for a piece of code that can be tested first and then implemented. This approach is like "test
a little, code a little, test a little, code a little." It increases the productivity of the programmer and
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 1/64
7/24/22, 12:30 AM JUnit - Quick Guide
the stability of program code, which in turn reduces the stress on the programmer and the time
spent on debugging.
Features of JUnit
JUnit is an open source framework, which is used for writing and running tests.
JUnit tests allow you to write codes faster, which increases 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 the test is running smoothly, and it turns
red when a test fails.
A formal written unit test case is characterized by a known input and 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 unit 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.
System Requirement
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 2/64
7/24/22, 12:30 AM JUnit - Quick Guide
OS Task Command
OS Output
If you do not have Java installed on your system, then download the Java Software Development
Kit (SDK) from the following link https://www.oracle.com . We are assuming Java 1.8.0_101 as
the installed version for this tutorial.
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 3/64
7/24/22, 12:30 AM JUnit - Quick Guide
OS Output
OS Output
Verify Java installation using the command java -version as explained above.
OS Archive name
Windows junit4.12.jar
Linux junit4.12.jar
Mac junit4.12.jar
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 4/64
7/24/22, 12:30 AM JUnit - Quick Guide
1
Windows
2
Linux
3
Mac
1
Windows
2
Linux
3
Mac
import org.junit.Test;
import static org.junit.Assert.assertEquals;
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 5/64
7/24/22, 12:30 AM JUnit - Quick Guide
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;
System.out.println(result.wasSuccessful());
}
}
C:\JUNIT_WORKSPACE>java TestRunner
true
Eclipse
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 6/64
7/24/22, 12:30 AM JUnit - Quick Guide
Ant
Maven
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.*;
Test Suites
A test suite bundles a few unit test cases and runs them together. In JUnit, both @RunWith and
@Suite annotation are used to run the suite test. Given below is an example that uses TestJunit1
& TestJunit2 test classes.
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 7/64
7/24/22, 12:30 AM JUnit - Quick Guide
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@Suite.SuiteClasses({
TestJunit1.class ,TestJunit2.class
})
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
@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());
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 8/64
7/24/22, 12:30 AM JUnit - Quick Guide
}
}
Test Runners
Test runner is used for executing the test cases. Here is an example that assumes the test class
TestJunit already exists.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
JUnit Classes
JUnit classes are important classes, used in writing and testing JUnits. Some of the important
classes are −
TestCase − Contains a test case that defines the fixture to run multiple tests.
TestResult − Contains methods to collect the results of executing a test case.
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.
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 9/64
7/24/22, 12:30 AM JUnit - Quick Guide
*/
//Constructor
//@param message to be printed
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Compile the MessageUtil, Test case and Test Runner classes using javac.
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Hello World
true
Now update TestJunit in C:\>JUNIT_WORKSPACE so that the test fails. Change the message
string.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 11/64
7/24/22, 12:30 AM JUnit - Quick Guide
@Test
public void testPrintMessage() {
message = "New Word";
assertEquals(message,messageUtil.printMessage());
}
}
Let's keep the rest of the classes as is, and try to run the same Test Runner.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Hello World
testPrintMessage(TestJunit): expected:<[New Wor]d> but was:<[Hello Worl]d>
false
JUnit - API
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 12/64
7/24/22, 12:30 AM JUnit - Quick Guide
The most important package in JUnit is junit.framework, which contains all the core classes.
Some of the important classes are as follows −
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 as follows −
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 13/64
7/24/22, 12:30 AM JUnit - Quick Guide
1
void assertEquals(boolean expected, boolean actual)
2
void assertFalse(boolean condition)
3
void assertNotNull(Object object)
4
void assertNull(Object object)
5
void assertTrue(boolean condition)
6
void fail()
Let's use some of the above-mentioned methods in an example. Create a java class file named
TestJunit1.java in C:\>JUNIT_WORKSPACE.
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Compile the test case and Test Runner classes using javac.
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner1
true
TestCase Class
Following is the declaration for org.junit.TestCase class −
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 15/64
7/24/22, 12:30 AM JUnit - Quick Guide
A test case defines the fixture to run multiple tests. Some of the important methods of TestCase
class are as follows −
1
int countTestCases()
2
TestResult createResult()
3
String getName()
4
TestResult run()
A convenience method to run this test, collecting the results with a default TestResult
object.
5
void run(TestResult result)
6
void setName(String name)
7
void setUp()
8
void tearDown()
9
String toString()
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 16/64
7/24/22, 12:30 AM JUnit - Quick Guide
Let's use some of the above-mentioned methods in an example. Create a java class file named
TestJunit2.java in C:\>JUNIT_WORKSPACE.
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
@Before
public void setUp() {
fValue1 = 2.0;
fValue2 = 3.0;
}
@Test
public void testAdd() {
//count the number of test cases
System.out.println("No of Test Case = "+ this.countTestCases());
//test getName
String name = this.getName();
System.out.println("Test Case Name = "+ name);
//test setName
this.setName("testNewAdd");
String newName = this.getName();
System.out.println("Updated Test Case Name = "+ newName);
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Compile the test case and Test Runner classes using javac.
Now run the Test Runner, which will run the test case defined in the 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 as
follows −
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 18/64
7/24/22, 12:30 AM JUnit - Quick Guide
1
void addError(Test test, Throwable t)
2
void addFailure(Test test, AssertionFailedError t)
3
void endTest(Test test)
4
int errorCount()
5
Enumeration<TestFailure> errors()
6
int failureCount()
7
void run(TestCase test)
Runs a TestCase.
8
int runCount()
9
void startTest(Test test)
10
void stop()
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 19/64
7/24/22, 12:30 AM JUnit - Quick Guide
import org.junit.Test;
import junit.framework.AssertionFailedError;
import junit.framework.TestResult;
@Test
public void testAdd() {
// add any test
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 20/64
7/24/22, 12:30 AM JUnit - Quick Guide
Compile the test case and Test Runner classes using javac.
Now run the Test Runner, which will run the test case defined in the 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 as follows −
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 21/64
7/24/22, 12:30 AM JUnit - Quick Guide
1
void addTest(Test test)
2
void addTestSuite(Class<? extends TestCase> testClass)
3
int countTestCases()
Counts the number of test cases that will be run by this test.
4
String getName()
5
void run(TestResult result)
6
void setName(String name)
7
Test testAt(int index)
8
int testCount()
9
static Test warning(String message)
import junit.framework.*;
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
/**
* @return the name
*/
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 23/64
7/24/22, 12:30 AM JUnit - Quick Guide
/**
* @param name the name to set
*/
/**
* @return the monthlySalary
*/
/**
* @param monthlySalary the monthlySalary to set
*/
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
return appraisal;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 25/64
7/24/22, 12:30 AM JUnit - Quick Guide
employee.setMonthlySalary(8000);
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Compile the test case and Test Runner classes using javac.
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 26/64
7/24/22, 12:30 AM JUnit - Quick Guide
C:\JUNIT_WORKSPACE>javac EmployeeDetails.java
EmpBusinessLogic.java TestEmployeeDetails.java TestRunner.java
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
true
Assertion
All the assertions are in the 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 as follows −
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 27/64
7/24/22, 12:31 AM JUnit - Quick Guide
1
void assertEquals(boolean expected, boolean actual)
2
void assertTrue(boolean condition)
3
void assertFalse(boolean condition)
4
void assertNotNull(Object object)
5
void assertNull(Object object)
6
void assertSame(object1, object2)
The assertSame() method tests if two object references point to the same object.
7
void assertNotSame(object1, object2)
The assertNotSame() method tests if two object references do not point to the same
object.
8
void assertArrayEquals(expectedArray, resultArray);
The assertArrayEquals() method will test whether two arrays are equal to each other.
Let's use some of the above-mentioned methods in an example. Create a java class file named
TestAssertions.java in C:\>JUNIT_WORKSPACE.
import org.junit.Test;
import static org.junit.Assert.*;
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 28/64
7/24/22, 12:31 AM JUnit - Quick Guide
@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;
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 29/64
7/24/22, 12:31 AM JUnit - Quick Guide
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac.
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
true
Annotation
Annotations are like meta-tags that you can add to your code, and apply them to methods or in
class. These annotations in JUnit provide the following information about test methods −
which methods are going to run before and after test methods.
which methods run before and after all the methods, and.
which methods or classes will be ignored during the execution.
The following table provides a list of annotations and their meaning in JUnit −
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 30/64
7/24/22, 12:31 AM JUnit - Quick Guide
1
@Test
The Test annotation tells JUnit that the public void method to which it is attached can
be run as a test case.
2
@Before
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.
3
@After
If you allocate external resources in a Before method, you need to release them after
the test runs. Annotating a public void method with @After causes that method to be
run after the Test method.
4
@BeforeClass
Annotating a public static void method with @BeforeClass causes it to be run once
before any of the test methods in the class.
5
@AfterClass
This will perform the method after all tests have finished. This can be used to perform
clean-up activities.
6
@Ignore
The Ignore annotation is used to ignore the test and that test will not be executed.
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 31/64
7/24/22, 12:31 AM JUnit - Quick Guide
//test case
@Test
public void test() {
System.out.println("in test");
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 32/64
7/24/22, 12:31 AM JUnit - Quick Guide
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac.
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
in before class
in before
in test
in after
in after class
true
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 33/64
7/24/22, 12:31 AM JUnit - Quick Guide
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");
}
//test case 2
@Test
public void testCase2() {
System.out.println("in test case 2");
}
}
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 34/64
7/24/22, 12:31 AM JUnit - Quick Guide
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac.
Now run the Test Runner, which will run the test case defined in the 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
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 35/64
7/24/22, 12:31 AM JUnit - Quick Guide
Here we will see how to 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.
*/
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 36/64
7/24/22, 12:31 AM JUnit - Quick Guide
Implement the test condition and check the condition using assertEquals API of JUnit.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac.
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 37/64
7/24/22, 12:31 AM JUnit - Quick Guide
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Hello World
true
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.
*/
//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;
@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());
}
}
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestJunit1.class,
TestJunit2.class
})
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 40/64
7/24/22, 12:31 AM JUnit - Quick Guide
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Inside testPrintMessage()
Robert
Inside testSalutationMessage()
Hi Robert
true
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.
*/
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 41/64
7/24/22, 12:31 AM JUnit - Quick Guide
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());
}
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 42/64
7/24/22, 12:31 AM JUnit - Quick Guide
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Compile the MessageUtil, Test case and Test Runner classes using javac.
Now run the Test Runner, which will not run the testPrintMessage() test case defined in the
provided Test Case class.
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 {
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 43/64
7/24/22, 12:31 AM JUnit - Quick Guide
@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
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Now run the Test Runner, which will not run any test case defined in the provided Test Case
class.
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 44/64
7/24/22, 12:31 AM JUnit - Quick Guide
C:\JUNIT_WORKSPACE>java TestRunner
true
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.
*/
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 45/64
7/24/22, 12:31 AM JUnit - Quick Guide
}
}
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;
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 46/64
7/24/22, 12:31 AM JUnit - Quick Guide
System.out.println(result.wasSuccessful());
}
}
Compile the MessageUtil, Test case and Test Runner classes using javac.
Now run the Test Runner, which will run the test cases defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output. testPrintMessage() test case will mark the unit testing failed.
Inside testPrintMessage()
Robert
Inside testSalutationMessage()
Hi!Robert
testPrintMessage(TestJunit): test timed out after 1000 milliseconds
false
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.
*/
//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;
@Test(expected = ArithmeticException.class)
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
messageUtil.printMessage();
}
@Test
public void testSalutationMessage() {
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 48/64
7/24/22, 12:31 AM JUnit - Quick Guide
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;
System.out.println(result.wasSuccessful());
}
}
Compile the MessageUtil, Test case and Test Runner classes using javac.
Now run the Test Runner, which will run the test cases defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Inside testPrintMessage()
Robert
Inside testSalutationMessage()
Hi!Robert
true
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 49/64
7/24/22, 12:31 AM JUnit - Quick Guide
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 test case(s) using the instance variables as the source of the test data.
The test case will be invoked once for each row of data. Let us see parameterized tests in action.
Create a Class
Create a java class to be tested, say, PrimeNumberChecker.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;
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 50/64
7/24/22, 12:31 AM JUnit - Quick Guide
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;
System.out.println(result.wasSuccessful());
}
}
Now run the Test Runner, which will run the test cases defined in the 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
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 52/64
7/24/22, 12:31 AM JUnit - Quick Guide
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
1
Windows
2
Linux
3
Mac
OS Output
Windows Append the string %ANT_HOME\bin at the end of the system variable, Path.
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 53/64
7/24/22, 12:31 AM JUnit - Quick Guide
OS Archive Name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar
/*
* This class prints the given message on console.
*/
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 54/64
7/24/22, 12:31 AM JUnit - Quick Guide
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
@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());
}
}
<path id = "classpath.base"/>
<path id = "classpath.test">
<pathelement location = "lib/junit-4.10.jar" />
<pathelement location = "${testdir}" />
<pathelement location = "${srcdir}" />
<path refid = "classpath.base" />
</path>
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 55/64
7/24/22, 12:31 AM JUnit - Quick Guide
</project>
C:\JUNIT_WORKSPACE\TestJunitWithAnt>ant
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)]
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 56/64
7/24/22, 12:31 AM JUnit - Quick Guide
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
OS Archive Name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar
Assume you have copied the above JAR file onto the folder C:\>JUnit.
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.
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 58/64
7/24/22, 12:31 AM JUnit - Quick Guide
/*
* This class prints the given message on console.
*/
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
Finally, right click the program and run as JUnit to verify the output of the program.
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 60/64
7/24/22, 12:31 AM JUnit - Quick Guide
JUnit - Extensions
Following are the 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 that executes the tests inside a
container.
Cactus Framework is the heart of Cactus. It is the engine that provides the API to write
Cactus tests.
Cactus Integration Modules are front-ends and frameworks that provide easy ways of
using the Cactus Framework (Ant scripts, Eclipse plugin, and Maven plugin).
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 61/64
7/24/22, 12:31 AM JUnit - Quick Guide
import org.apache.cactus.*;
import junit.framework.*;
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 test the
correctness of your web applications.
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.
import junit.framework.TestCase;
import net.sourceforge.jwebunit.WebTester;
XMLUnit
XMLUnit provides a single JUnit extension class, XMLTestCase, and a set of supporting classes
that allow assertions to be made about −
The differences between two pieces of XML (via Diff and DetailedDiff classes).
The outcome of transforming a piece of XML using XSLT (via Transform class).
The evaluation of an XPath expression on a piece of XML (via classes implementing the
XpathEngine interface).
Individual nodes in a piece of XML that are exposed by DOM Traversal (via NodeTest
class).
Let us assume we have two pieces of XML that we wish to compare and assert that they are
equal. We could write a simple test class like this −
import org.custommonkey.xmlunit.XMLTestCase;
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.
import org.jmock.Mockery;
import org.jmock.Expectations;
// expectations
context.checking(new Expectations() {
oneOf (sub).receive(message);
});
// execute
pub.publish(message);
// verify
context.assertIsSatisfied();
}
}
https://www.tutorialspoint.com/junit/junit_quick_guide.htm 64/64