JUnit Tutorial
JUnit Tutorial
JUnit Tutorial
This tutorial explains the use of JUnit in your project unit testing, while
working with Java. After completing this tutorial you will gain sufficient
knowledge in using JUnit testing framework from where you can take
yourself to next levels.
Audience
This tutorial has been prepared for beginners to help them understand
the basic functionality of JUnit tool.
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 the knowledge of
software development using any programming language, especially Java
programming and software testing process.
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 Taking tool support and executing the
without any tool support is known as test cases by using an automation tool is
manual testing. known as automation testing.
Less reliable − Manual testing is less More reliable − Automation tests are
reliable, as it has to account for precise and reliable.
human 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
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.
Provides annotations to identify test methods.
Provides assertions for testing expected results.
Provides test runners for running tests.
JUnit tests allow you to write codes faster, which increases quality.
JUnit is elegantly simple. It is less complex and takes less time.
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.
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
JDK 1.5 or above.
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.
OS Output
Windows Set the environment variable JAVA_HOME to C:\Program
Files\Java\jdk1.8.0_101
OS Output
OS Archive name
Windows junit4.12.jar
Linux junit4.12.jar
Mac junit4.12.jar
Step 4: Set JUnit Environment
Set the JUNIT_HOME environment variable to point to the base
directory location where JUNIT jar is stored on your machine. Let’s
assuming we've stored junit4.12.jar in the JUNIT folder.
1
Windows
2 Linux
3
Mac
1
Windows
2 Linux
3
Mac
@Test
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
}
Step 7: Verify the Result
Compile the classes using javac compiler as follows −
C:\JUNIT_WORKSPACE>javac TestJunit.java TestRunner.java
Eclipse
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.*;
public class JavaTest extends TestCase {
value1 = 3;
value2 = 3;
assertTrue(result == 6);
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.
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.Test;
import org.junit.Ignore;
@Test
System.out.println("Inside testPrintMessage()");
assertEquals(message, messageUtil.printMessage());
import org.junit.Test;
import org.junit.Ignore;
@Test
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
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(failure.toString());
System.out.println(result.wasSuccessful());
JUnit Classes
JUnit classes are important classes, used in writing and testing JUnits.
Some of the important classes are −
Create a Class
Create a java class to be tested, say, MessageUtil.java
in C:\>JUNIT_WORKSPACE
/*
*/
//Constructor
this.message = message;
System.out.println(message);
return message;
}
Create Test Case Class
Create a java test class, say, TestJunit.java.
Implement the test condition and check the condition using assertEquals API
of JUnit.
import org.junit.Test;
@Test
assertEquals(message,messageUtil.printMessage());
Use runClasses method of JUnitCore class of JUnit to run the test case of the
above created test class.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
Compile the MessageUtil, Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.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
import org.junit.Test;
@Test
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(failure.toString());
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
JUnit - API
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 −
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 as follows −
1
void assertEquals(boolean expected, boolean actual)
4
void assertNull(Object object)
6
void fail()
import org.junit.Test;
@Test
//test data
int num = 5;
assertNotNull(temp);
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
Compile the test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac TestJunit1.java TestRunner1.java
Now run the Test Runner, which will run the test case defined in the
provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner1
TestCase Class
Following is the declaration for org.junit.TestCase class −
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 as follows −
1
int countTestCases()
2 TestResult createResult()
3
String getName()
4 TestResult run()
5
void run(TestResult result)
7
void setUp()
8 void tearDown()
Tears down the fixture, for example, close a network connection.
9 String toString()
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
@Before
fValue1 = 2.0;
fValue2 = 3.0;
@Test
//test getName
this.setName("testNewAdd");
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
Compile the test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac TestJunit2.java TestRunner2.java
Now run the Test Runner, which will run the test case defined in the
provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner2
TestResult Class
Following is the declaration for org.junit.TestResult class −
public class TestResult extends Object
1
void addError(Test test, Throwable t)
3
void endTest(Test test)
4 int errorCount()
5
Enumeration<TestFailure> errors()
Runs a TestCase.
8
int runCount()
10
void stop()
import org.junit.Test;
import junit.framework.AssertionFailedError;
import junit.framework.TestResult;
}
@Test
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
Compile the test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac TestJunit3.java TestRunner3.java
Now run the Test Runner, which will run the test case defined in the
provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner3
TestSuite Class
Following is the declaration for org.junit.TestSuite class:
public class TestSuite extends Object implements Test
1
void addTest(Test test)
3
int countTestCases()
Counts the number of test cases that will be run by this test.
4 String getName()
5
void run(TestResult result)
7
Test testAt(int index)
Returns the test at the given index.
8 int testCount()
9
static Test warning(String message)
import junit.framework.*;
suite.run(result);
/**
*/
return name;
/**
*/
this.name = name;
/**
* @return the monthlySalary
*/
return monthlySalary;
/**
*/
this.monthlySalary = monthlySalary;
/**
*/
return age;
/**
*/
this.age = age;
}
EmployeeDetails class is used to −
double yearlySalary = 0;
return yearlySalary;
double appraisal = 0;
appraisal = 500;
}else{
appraisal = 1000;
return appraisal;
import org.junit.Test;
@Test
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
@Test
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
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 the test case defined in the
provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
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 −
2
void assertTrue(boolean condition)
4
void assertNotNull(Object object)
6
void assertSame(object1, object2)
The assertArrayEquals() method will test whether two arrays are equal
to each other.
import org.junit.Test;
@Test
//test data
int val1 = 5;
int val2 = 6;
assertEquals(str1, str2);
//Check that a condition is true
assertNotNull(str1);
assertNull(str3);
assertSame(str4,str5);
assertNotSame(str1,str3);
assertArrayEquals(expectedArray, resultArray);
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner2 {
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac TestAssertions.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
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.
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
4 @BeforeClass
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;
@BeforeClass
@AfterClass
@Before
System.out.println("in before");
@After
System.out.println("in after");
}
//test case
@Test
System.out.println("in test");
@Ignore
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
}
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac JunitAnnotation.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
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
@BeforeClass
@AfterClass
@Before
System.out.println("in before");
@After
System.out.println("in after");
//test case 1
@Test
//test case 2
@Test
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac ExecutionProcedureJunit.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
The before() method executes for each test case, but before executing the
test case.
The after() method executes for each test case, but after the execution of
test case.
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.
/*
*/
//Constructor
//@param message to be printed
this.message = message;
System.out.println(message);
return message;
import org.junit.Test;
@Test
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.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
Create a Class
Create a java class to be tested, say, MessageUtil.java in
C:\>JUNIT_WORKSPACE.
/*
*/
//Constructor
this.message = message;
System.out.println(message);
return message;
System.out.println(message);
return message;
import org.junit.Test;
import org.junit.Ignore;
@Test
System.out.println("Inside testPrintMessage()");
assertEquals(message, messageUtil.printMessage());
import org.junit.Test;
import org.junit.Ignore;
@Test
System.out.println("Inside testSalutationMessage()");
assertEquals(message,messageUtil.salutationMessage());
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;
System.out.println(failure.toString());
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
Create a Class
Create a java class to be tested, say, MessageUtil.java in
C:\>JUNIT_WORKSPACE.
/*
*/
//Constructor
this.message = message;
System.out.println(message);
return message;
}
// add "Hi!" to the message
System.out.println(message);
return message;
import org.junit.Test;
import org.junit.Ignore;
@Ignore
@Test
System.out.println("Inside testPrintMessage()");
message = "Robert";
assertEquals(message,messageUtil.printMessage());
@Test
System.out.println("Inside testSalutationMessage()");
assertEquals(message,messageUtil.salutationMessage());
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
}
Compile the MessageUtil, Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java
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
import org.junit.Test;
import org.junit.Ignore;
@Ignore
@Test
System.out.println("Inside testPrintMessage()");
message = "Robert";
assertEquals(message,messageUtil.printMessage());
@Test
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(failure.toString());
System.out.println(result.wasSuccessful());
Now run the Test Runner, which will not run any test case defined in the
provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Create a Class
Create a java class to be tested, say, MessageUtil.java in
C:\>JUNIT_WORKSPACE.
/*
*/
//Constructor
this.message = message;
System.out.println(message);
while(true);
System.out.println(message);
return message;
import org.junit.Test;
import org.junit.Ignore;
@Test(timeout = 1000)
System.out.println("Inside testPrintMessage()");
messageUtil.printMessage();
@Test
System.out.println("Inside testSalutationMessage()");
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
Compile the MessageUtil, Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java
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.
/*
*/
//Constructor
this.message = message;
System.out.println(message);
int a = 0;
int b = 1/a;
}
System.out.println(message);
return message;
import org.junit.Test;
import org.junit.Ignore;
@Test(expected = ArithmeticException.class)
System.out.println("Inside testPrintMessage()");
messageUtil.printMessage();
}
@Test
System.out.println("Inside testSalutationMessage()");
assertEquals(message,messageUtil.salutationMessage());
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
System.out.println(result.wasSuccessful());
Compile the MessageUtil, Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java
Now run the Test Runner, which will run the test cases defined in the
provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
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.
if (primeNumber % i == 0) {
return false;
return true;
}
}
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;
@RunWith(Parameterized.class)
@Before
this.inputNumber = inputNumber;
this.expectedResult = expectedResult;
@Parameterized.Parameters
{ 2, true },
{ 6, false },
{ 19, true },
{ 22, false },
{ 23, true }
});
@Test
assertEquals(expectedResult,
primeNumberChecker.validate(inputNumber));
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
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
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
OS Archive Name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar
/*
*/
//Constructor
//@param message to be printed
this.message = message;
System.out.println(message);
return message;
System.out.println(message);
return message;
import org.junit.Test;
import org.junit.Ignore;
System.out.println("Inside testPrintMessage()");
assertEquals(message,messageUtil.printMessage());
@Test
System.out.println("Inside testSalutationMessage()");
assertEquals(message,messageUtil.salutationMessage());
<path id = "classpath.base"/>
<path id = "classpath.test">
</delete>
</target>
verbose = "${full-compile}">
</javac>
</target>
<junit>
</junit>
</target>
</project>
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
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.
Now your Eclipse is ready for the development of JUnit test cases.
/*
*/
//Constructor
this.message = message;
System.out.println(message);
return message;
@Test
assertEquals(message,messageUtil.printMessage());
Finally, right click the program and run as JUnit to verify the output of
the program.
Verify the result.
JU
nit - 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.
import org.apache.cactus.*;
import junit.framework.*;
@Test
session.setAttribute("name", "value");
assertEquals("something", result);
assertEquals("otherValue", session.getAttribute("otherName"));
}
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.
import junit.framework.TestCase;
import net.sourceforge.jwebunit.WebTester;
super(name);
getTestContext().setBaseUrl("http://myserver:8080/myapp");
beginAt("/info.html");
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 validity of a piece of XML (via Validator class).
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;
@Test
}
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;
// set up
pub.add(sub);
// expectations
context.checking(new Expectations() {
oneOf (sub).receive(message);
});
// execute
pub.publish(message);
// verify
context.assertIsSatisfied();