Java JUnit Unit Testing Framework
JUnit is one of the most popular unit testing frameworks in the Java programming language, used to write and run repeatable automated tests.
JUnit was created by Kent Beck and Erich Gamma and is a member of the xUnit family. Unit testing refers to the process of inspecting and verifying the smallest testable parts of software (usually methods or classes).
The main features of JUnit include:
- Provides annotations to mark test methods
- Provides assertions to verify expected results
- Supports test suites
- Provides test runners
Why Do We Need Unit Testing?
Unit testing is an indispensable part of modern software development; it brings the following benefits:
- Find Problems Early: Discover and fix errors during development
- Improve Code Quality: Forces developers to write more modular, testable code
- Documentation Effect: Test cases themselves are the best documentation of code behavior
- Refactoring Safety Net: Ensures that modifying code does not break existing functionality
- Reduce Debugging Time: Quickly locate where problems are
Using JUnit in a Project
For JUnit 5:
org.junit.jupiter
junit-jupiter
5.8.2
test
For JUnit 4:
junit
junit
4.13.2
test
JUnit 5 Basics
JUnit 5 is the latest version and consists of three main modules:
- JUnit Platform (the foundation for running tests)
- JUnit Jupiter (the new programming and extension model)
- JUnit Vintage (supports running JUnit 3 and 4 tests)
Basic Annotations
Legacy annotations:
-
@Test: Marks a method as a test method -
@Before: Executed before each test method -
@After: Executed after each test method -
@BeforeClass: Executed before all tests (static method) -
@AfterClass: Executed after all tests (static method) -
@Ignore: Ignore a test method
Example
import
org.junit.*
;
public
class
CalculatorTest
{
@BeforeClass
public
static
void
setUpBeforeClass
(
)
{
System
.
out
.
println
(
"Before all tests"
)
;
}
@Before
public
void
setUp
(
)
{
System
.
out
.
println
(
"Before each test"
)
;
}
@Test
public
void
testAddition
(
)
{
Calculator calculator
=
new
Calculator
(
)
;
int
result
=
calculator.
add
(
2
,
3
)
;
Assert
.
assertEquals
(
5
, result
)
;
}
@Test
@Ignore
(
"Not implemented yet"
)
public
void
testSubtraction
(
)
{
// Test code
}
@After
public
void
tearDown
(
)
{
System
.
out
.
println
(
"After each test"
)
;
}
@AfterClass
public
static
void
tearDownAfterClass
(
)
{
System
.
out
.
println
(
"After all tests"
)
;
}
}
JUnit 5 is a new-generation version; the new annotations are as follows:
-
@BeforeEachreplaces@Before -
@AfterEachreplaces@After -
@BeforeAllreplaces@BeforeClass -
@AfterAllreplaces@AfterClass -
@Disabledreplaces@Ignore
Example
import
org.junit.jupiter.api.*
;
@Test
void
testMethod
(
)
{
// Test code
}
@BeforeEach
void
setUp
(
)
{
// Executed before each test method runs
}
@AfterEach
void
tearDown
(
)
{
// Executed after each test method runs
}
@BeforeAll
static
void
initAll
(
)
{
// Executed once before all test methods run
}
@AfterAll
static
void
tearDownAll
(
)
{
// Executed once after all test methods run
}
Common Assertion Methods
JUnit provides a rich set of assertion methods to verify test results:
-
assertEquals(expected, actual) -
assertTrue(condition) -
assertFalse(condition) -
assertNull(object) -
assertNotNull(object) -
assertSame(expected, actual)(checks whether they are the same object) -
assertNotSame(unexpected, actual) -
assertArrayEquals(expectedArray, actualArray)
Example
import
static
org.
junit
.
jupiter
.
api
.
Assertions
.
*;
@Test
void
testAssertions
(
)
{
// Equality assertion
assertEquals
(
expected, actual
)
;
// True assertion
assertTrue
(
condition
)
;
// Null assertion
assertNull
(
object
)
;
// Exception assertion
assertThrows
(
ExpectedException.
class
,
(
)
->
{
// Code that throws an exception
}
)
;
// Timeout assertion
assertTimeout
(
Duration.
ofMillis
(
100
)
,
(
)
->
{
// Code that should complete within the specified time
}
)
;
}
Writing Your First JUnit Test
Let us learn how to write a JUnit test through a simple example.
1. Create the class under test
Example
public
class
Calculator
{
public
int
add
(
int
a,
int
b
)
{
return
a
b
;
}
public
int
divide
(
int
a,
int
b
)
{
if
(
b
==
0
)
{
throw
new
ArithmeticException
(
"Divisor cannot be zero"
)
;
}
return
a
/
b
;
}
}
2. Create the test class
Example
import
org.junit.jupiter.api.*
;
import
static
org.
junit
.
jupiter
.
api
.
Assertions
.
*;
class
CalculatorTest
{
private
Calculator calculator
;
@BeforeEach
void
setUp
(
)
{
calculator
=
new
Calculator
(
)
;
}
@Test
void
testAdd
(
)
{
assertEquals
(
5
, calculator.
add
(
2
,
3
)
)
;
}
@Test
void
testDivide
(
)
{
assertEquals
(
2
, calculator.
divide
(
6
,
3
)
)
;
}
@Test
void
testDivideByZero
(
)
{
assertThrows
(
ArithmeticException
.
class
,
(
)
->
{
calculator.
divide
(
1
,
0
)
;
}
)
;
}
}
JUnit Advanced Features
Parameterized Tests
JUnit 5 provides the @ParameterizedTest annotation, which allows running the same test multiple times with different parameters:
Example
@ParameterizedTest
@ValueSource
(
ints
=
{
1
,
2
,
3
}
)
void
testWithValueSource
(
int
argument
)
{
assertTrue
(
argument
0
&&
argument
<
4
);
}
Test Lifecycle
Understanding the JUnit test lifecycle is important for writing effective tests:
@BeforeAllmethod executes (once only)- For each test method:
@BeforeEach method executes@AfterEach method executes@AfterAllmethod executes (once only)
Test Suites
You can use the @Suite annotation combines multiple test classes to run together:
Example
import
org.junit.platform.suite.api.SelectClasses
;
import
org.junit.platform.suite.api.Suite
;
@Suite
@SelectClasses
(
{
CalculatorTest.
class
, AnotherTest.
class
}
)
public
class
TestSuite
{
}
Best Practices
- Test Naming: Test method names should clearly express their intent, such as
shouldReturnTrueWhenInputIsValid() - Single Responsibility: Each test method tests only one feature point
- Independent Tests: There should be no dependencies between tests
- Fast Feedback: Keep tests running fast
- Test Coverage: Pursue reasonable coverage, but do not blindly pursue 100%
- Test Data: Use meaningful test data
- Avoid Testing Implementation Details: Test behavior rather than implementation
Frequently Asked Questions
What is the difference between JUnit 4 and JUnit 5?
The main differences include:
- JUnit 5 requires Java 8 or higher
- Annotations moved from the
org.junitpackage to theorg.junit.jupiter.apipackage @Beforeand@Afterto@BeforeEachand@AfterEach@BeforeClassand@AfterClassto@BeforeAlland@AfterAll- JUnit 5 introduced an extension model to replace JUnit 4's rules
How to Run JUnit Tests?
You can run JUnit tests in the following ways:
- Right-click the test class or method in the IDE and select "Run"
- Using Maven:
mvn test - Using Gradle:
gradle test - Using the JUnit Console Launcher
How to Test Private Methods?
It is generally not recommended to test private methods directly; instead, indirectly test them through public methods. If you must test private methods, consider:
- Using reflection
- Change the method to package-private (no modifier) and create a test class with the same package structure under the test directory
- Refactor the code to extract the private method's logic into a separate class
Summary
JUnit is an essential testing tool for Java developers; mastering it can significantly improve code quality and development efficiency. Start with simple unit tests and gradually learn more advanced features, such as parameterized tests and test suites. Remember, good tests should be valued as much as production code, and keeping test code clean and maintainable is equally important.
Common Java Libraries