Junit
Junit
#junit
Table of Contents
About 1
Remarks 2
Versions 2
Examples 2
Installation or Setup 2
@Before, @After 4
Ignoring Tests 6
Remarks 8
Examples 8
Introduction 10
Examples 10
Introduction 11
Examples 11
Introduction 12
Syntax 12
Remarks 12
Examples 12
Using a Constructor 12
Syntax 14
Examples 14
Default Order 14
Lexicographical Order 15
Examples 16
Chapter 8: Tests 18
Remarks 18
Examples 18
Fixtures 20
Performance measurement 23
Credits 25
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: junit
It is an unofficial and free junit ebook created for educational purposes. All the content is extracted
from Stack Overflow Documentation, which is written by many hardworking individuals at Stack
Overflow. It is neither affiliated with Stack Overflow nor official junit.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ 1
Chapter 1: Getting started with junit
Remarks
JUnit is a simple framework to write repeatable tests for Java programming language. It is an
instance of the xUnit architecture for unit testing frameworks.
• Assertions, that let you customize how to test values in your tests
• Test runners, that let you specify how to run the tests in your class
• Rules, that allow you to flexibly modify the behaviour of tests in your class
• Suites, that allow you to build together a suite of tests from many different classes
Versions
Version ReleaseDate
Examples
Installation or Setup
Since JUnit is a Java library, all you have to do to install it is to add a few JAR files into the
https://riptutorial.com/ 2
classpath of your Java project and you're ready to go.
You can download these two JAR files manually: junit.jar & hamcrest-core.jar.
If you're using Maven, you can simply add in a dependency into your pom.xml:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
dependencies {
testCompile 'junit:junit:4.12'
}
import org.junit.Test;
This example is a basic setup for unittesting the StringBuilder.toString() using junit.
import org.junit.Test;
@Test
https://riptutorial.com/ 3
public void stringBuilderAppendShouldConcatinate() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("String");
stringBuilder.append("Builder");
stringBuilder.append("Test");
assertEquals("StringBuilderTest", stringBuilder.toString());
}
@Before, @After
An annotated method with @Before will be executed before every execution of @Test methods.
Analogous an @After annotated method gets executed after every @Test method. This can be used
to repeatedly set up a Test setting and clean up after every test. So the tests are independent and
preparation code is not copied inside the @Test method.
Example:
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@Before
public void setUp() {
list = new ArrayList<>();
list.add(3);
list.add(1);
list.add(4);
list.add(1);
list.add(5);
list.add(9);
}
@After
public void tearDown() {
list.clear();
}
@Test
public void shouldBeOkToAlterTestData() {
list.remove(0); // Remove first element of list.
assertEquals(5, list.size()); // Size is down to five
}
@Test
public void shouldBeIndependentOfOtherTests() {
assertEquals(6, list.size());
https://riptutorial.com/ 4
}
}
Methods annotated with @Before or @After must be public void and with zero arguments.
It is possible to easily catch the exception without any try catch block.
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
list.get(0);
}
}
The example above should suffice for simpler cases, when you don't want/need to check the
message carried by the thrown exception.
If you want to check information about exception you may want to use try/catch block:
@Test
public void testIndexOutOfBoundsException() {
try {
list.get(0);
Assert.fail("Should throw IndexOutOfBoundException");
} catch (IndexOutOfBoundsException ex) {
Assert.assertEquals("Index: 0, Size: 0", ex.getMessage());
}
}
For this example you have to be aware to always add Assert.fail() to ensure that test will be
failed when no Exception is thrown.
For more elaborated cases, JUnit has the ExpectedException @Rule, which can test this information
too and is used as follows:
@Test
public void throwsNothing() {
// no exception expected, none thrown: passes.
}
@Test
public void throwsExceptionWithSpecificType() {
expectedException.expect(NullPointerException.class);
https://riptutorial.com/ 5
@Test
public void throwsExceptionWithSpecificTypeAndMessage() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Wanted a donut.");
Ignoring Tests
To ignore a test, simply add the @Ignore annotation to the test and optionally provide a parameter
to the annotation with the reason.
https://riptutorial.com/ 6
}
Compared to commenting the test or removing the @Test annotation, the test runner will still report
this test and note that it was ignored.
It is also possible to ignore a test case conditionally by using JUnit assumptions. A sample use-
case would be to run the test-case only after a certain bug is fixed by a developer. Example:
import org.junit.Assume;
import org.junit.Assert;
...
@Test
public void testForBug1234() {
Assume.assumeTrue(isBugFixed(1234));//will not run this test until the bug 1234 is fixed
Assert.assertEquals(5, calculator.add(2,3));
}
The default runner treats tests with failing assumptions as ignored. It is possible that other runners
may behave differently e.g. treat them as passed.
https://riptutorial.com/ 7
Chapter 2: Custom Test Rules
Remarks
There are benefits for either. Extending ExternalResource it's convenient, especially if we only
require a before() to set something up.
However, we should be aware that, since the before() method is executed outside of the
try...finally, any code that is required to do clean up in after() won't get executed if there is an
error during the execution of before().
before();
try {
base.evaluate();
} finally {
after();
}
Obviously, if any exception is thrown in the test itself, or by another nested rule, the after will still
get executed.
Examples
Custom @TestRule by implementation
This is especially useful if we have a class that we want to extend in the rule. See example below
for a more convenient method.
import org.junit.rules.TestRule;
import org.junit.runners.model.Statement;
@Override
public Statement apply(Statement base, Description description) {
return new AwesomeStatement(base);
}
@Override
public void evaluate() throws Throwable {
try {
https://riptutorial.com/ 8
// do your magic
base.evaluate(); // this will call Junit to run an individual test
} finally {
// undo the magic, if required
}
}
}
JUnit has an abstract implementation of @TestRule that lets you write a rule in a more simpler way.
This is called ExternalResource and provides two protected methods that can be extended like this:
@Override
protected void before() {
// do your magic
}
@Override
protected void after() {
// undo your magic, if needed
}
https://riptutorial.com/ 9
Chapter 3: Generate Junit test cases skeleton
for existing code
Introduction
Sometimes you need to generate the skeleton for the test cases based on the classes you have in
your project.
Examples
Generate Junit test cases skeleton for existing code in Eclipse
Here are the steps to generate test skeleton for existing code:
1. Open Eclipse, and choose the project you want to create test cases for
2. In the Package Explorer, select the java class you want to generate the Junit test for
3. Go to File -> New -> Junit Test Cases
4. Change the Source folder to point to the test using Browse (Note: It is better to separate the
source code from the testing code)
5. Change the Package based on the destination package you want
6. In the Class under test, make sure you enter the class you want to generate the test cases
for.
7. Click Next
8. Select the methods you want to test for
9. Click Finish
Now, you will have a Junit class generated for testing the source class you have
Read Generate Junit test cases skeleton for existing code online:
https://riptutorial.com/junit/topic/8648/generate-junit-test-cases-skeleton-for-existing-code
https://riptutorial.com/ 10
Chapter 4: Ignore test cases in Junit
Introduction
Sometimes you want to ignore some of the test cases you have in Junit. For instance, they are
partially done and you want to come back to them later.
Examples
Ignore test case in Junit
https://riptutorial.com/ 11
Chapter 5: Paramaterizing Tests
Introduction
Sometimes you have a test you need to run multiple times, each time with different data.
Parameterizing the test allows you to do this in an easy and maintainable way.
Syntax
• @RunWith(Parameterized.class) //annotation for test class
Remarks
One benefit to using parameters is that if one set of data fails, execution will just move to the next
set of data instead of stopping the whole test.
Examples
Using a Constructor
@RunWith(Parameterized.class)
public class SimpleParmeterizedTest {
@Parameters
public static Collection<Object[]> data(){
return Arrays.asList(new Object[][]{
{5, false}, {6, true}, {8, true}, {11, false}
});
}
@Test
public void testIsEven(){
assertThat(isEven(input), is(expected));
https://riptutorial.com/ 12
}
}
In data() you supply the data to be used in the tests. Junit will iterate through the data and run the
test with each set of data.
https://riptutorial.com/ 13
Chapter 6: Test Execution Order
Syntax
• @FixMethodOrder // Runs test using default method sorter
• @FixMethodOrder(MethodSorters) // Runs test using MethodSorter associated with the
MethodSorters enum.
Examples
Default Order
Use the annotation -- @FixMethodOrder(MethodSorters.DEFAULT). This runs all tests within the class in
a deterministic and somewhat predictable order. The implementation hashes the method names
and compares them. In the scenario of a tie, it sorts by lexicographical order.
Example
@FixMethodOrder(MethodSorters.DEFAULT)
public class OrderedTest {
@Test
public void testA() {}
@Test
public void testB() {}
@Test
public void testC() {}
}
Suppose hashes for testA, testB, and testC are 3, 2, and 1 respectively. Then the execution order
is
1. testC
2. testB
3. testA
Suppose hashes for all tests are the same. Since all hashes are the same, execution order is
https://riptutorial.com/ 14
based on lexicographical order. The execution order is
1. testA
2. testB
3. testC
Lexicographical Order
Use the annotation @FixMethodOrder with the method sorter MethodSorters.NAME_ASCENDING. This will
run all tests within the class in a deterministic and predictable order. The implementation
compares the method names and in the case of a tie, it compares the methods' toString().
Example
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrderedTest {
@Test
public void testA() {}
@Test
public void testB() {}
@Test
public void testC() {}
}
1. testA
2. testB
3. testC
https://riptutorial.com/ 15
Chapter 7: Testing with DataProviders
Examples
Installation and usage
Installation:
Github
Direct download
Hamcrest-core-1.3.jar :
Github
Direct download
Usage:
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
@RunWith(DataProviderRunner.class)
@RunWith(DataProviderRunner.class)
public class example {
//code
}
@DataProvider
https://riptutorial.com/ 16
@DataProvider
public static Object[][] testExampleProvider() {
return new Object[][]{
{"param1", "param2", number1}
{"param1", "param2", number1}
//You can put as many parameters as you want
};
}
Before any function you want it to get those params that we return from the DataProvider, add this
decorator:
@UseDataProvider("testExampleProvider")
@Test
@UseDataProvider("testExampleProvider")
public void testAccount(String param1, String param2, int number) {
//System.out.println("exampleOfDataProviders");
//assertEquals(...);
//assertEquals(...);
}
https://riptutorial.com/ 17
Chapter 8: Tests
Remarks
@BeforeClass
public static void setupClass() {}
@Before
public void setupTest() {}
@Test
public void testA() {}
@Test
public void testB() {}
@After
public void tearDownTest() {}
@AfterClass
public static void tearDownClass() {}
}
}
Examples
Unit testing using JUnit
https://riptutorial.com/ 18
public static int countNumbers(String input) {
int count = 0;
for (char letter : input.toCharArray()) {
if (Character.isDigit(letter))
count++;
}
return count;
}
To unit test this class, we can use Junit framework. Add the junit.jar in your project class path.
Then create the Test case class as below:
@Test
public void hasNumberTest() {
boolean expectedValue = false;
boolean actualValue = Counter.hasNumber("Hi there!");
Assert.assertEquals(expectedValue, actualValue);
}
}
In your IDE you can run this class as "Junit testcase" and see the output in the GUI. In command
prompt you can compile and run the test case as below:
The output from a successful test run should look similar to:
OK (2 tests)
Time: 0.024
https://riptutorial.com/ 19
There was 1 failure:
1) CountNumbersTest(CounterTest)
java.lang.AssertionError: expected:<30> but was:<3>
... // truncated output
FAILURES!!!
Tests run: 2, Failures: 1
Fixtures
From Wikipedia:
A test fixture is something used to consistently test some item, device, or piece of
software.
It can also enhance readability of tests by extracting common initialisation / finalisation code from
the test methods themselves.
Where common initialisation can be executed once instead of before each tests, this can also
reduce the amount of time taken to run tests.
The example below is contrived to show the main options provided by JUnit. Assume a class Foo
which is expensive to initialise:
The tests below expect an initial context of a List containing a single Bar.
import java.util.Arrays;
import java.util.List;
https://riptutorial.com/ 20
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@BeforeClass
public static void setupOnce() {
// Called once before any tests have run
referenceFoo = new Foo();
}
@Before
public void setup() {
// Called before each test is run
testContext = Arrays.asList(new Bar(referenceFoo));
}
@Test
public void testSingle() {
assertEquals("Wrong test context size", 1, testContext.size());
Bar baz = testContext.get(0);
assertEquals(referenceFoo, baz.getFoo());
}
@Test
public void testMultiple() {
testContext.add(new Bar(referenceFoo));
assertEquals("Wrong test context size", 2, testContext.size());
for (Bar baz : testContext) {
assertEquals(referenceFoo, baz.getFoo());
}
}
@After
public void tearDown() {
// Called after each test is run
for (Bar baz : testContext) {
baz.cleanUp();
}
}
@AfterClass
public void tearDownOnce() {
// Called once after all tests have run
referenceFoo.cleanUp();
}
}
In the example the @BeforeClass annotated method setupOnce() is used to create the Foo object,
which is expensive to initialise. It is important that it not be modified by any of the tests, otherwise
the outcome of the test run could be dependent on the order of execution of the individual tests.
The idea is that each test is independent and tests one small feature.
https://riptutorial.com/ 21
The @Before annotated method setup() sets up the test context. The context may be modified
during test execution, which is why it must be initialised before each test. The equivalent effect
could be achieved by including the code contained in this method at the start of each test method.
The @After annotated method tearDown() cleans up resources within the test context. It is called
after each test invocation, and as such is often used to free resources allocated in a @Before
annotated method.
The @AfterClass annotated method tearDownOnce() cleans up resources once all tests have run.
Such methods are typically used to free resources allocated during initialisation or in a
@BeforeClass annotated method. That said, it's probably best to avoid external resources in unit
tests so that the tests don't depend on anything outside the test class.
From JavaDoc
The Theories runner allows to test a certain functionality against a subset of an infinite
set of data points.
Running theories
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
@RunWith(Theories.class)
public class FixturesTest {
@Theory
public void theory(){
//...some asserts
}
}
@DataPoint annotation
@RunWith(Theories.class)
public class FixturesTest {
@DataPoint
public static String dataPoint1 = "str1";
@DataPoint
public static String dataPoint2 = "str2";
@DataPoint
public static int intDataPoint = 2;
@Theory
public void theoryMethod(String dataPoint, int intData){
//...some asserts
}
}
https://riptutorial.com/ 22
Each field annotated with @DataPoint will be used as a method parameter of a given type in the
theories. In example above theoryMethod will run two times with following parameters: ["str1", 2] ,
["str2", 2]
@DataPoints
public static String[] dataPoints = new String[]{"str1", "str2"};
@DataPoints
public static int[] dataPoints = new int[]{1, 2};
@Theory
public void theoryMethod(String dataPoint, ){
//...some asserts
}
}
Each element of the array annotated with @DataPoints annotation will be used as a method
parameter of a given type in the theories. In example above theoryMethod will run four times with
following parameters: ["str1", 1], ["str2", 1], ["str1", 2], ["str2", 2]
Performance measurement
If you need to check if your testing method takes too long to execute, you can do that by
mentioning your expected execution time using timeout property of @Test annotation. If the test
execution takes longer than that number of milliseconds it causes a test method to fail.
// timeout in milliseconds
@Test(timeout = 20)
public void testString(){
System.out.println(res.length());
}
@Test(timeout = 20)
public void testStringBuilder(){
System.out.println(res.length());
}
https://riptutorial.com/ 23
@Test(timeout = 20)
public void testStringBuffer(){
System.out.println(res.length());
}
In most cases without JVM warm-up testString will fail. But testStringBuffer and testStringBuilder
should pass this test successfully.
https://riptutorial.com/ 24
Credits
S.
Chapters Contributors
No
Testing with
7 Manuel
DataProviders
https://riptutorial.com/ 25