Master the most popular testing framework for Java, through the Learn JUnit course:
Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
Unit Testing is a crucial step in software design and implementation.
It not only improves the efficiency and effectiveness of the code, but it also makes the code more robust and reduces the regressions in future development and maintenance.
In this tutorial, weβll discuss a few best practices for unit testing in Java.
2. What Is Unit Testing?
Unit Testing is a methodology of testing source code for its fitment of use in production.
We start out writing unit tests by creating various test cases to verify the behaviors of an individual unit of source code.
Then the complete test suite executes to catch the regressions, either in the implementation phase or while building packages for various stages of deployments such as staging and production.
Letβs take a look at a simple scenario.
To start with, letβs create the Circle class and implement the calculateArea method in it:
public class Circle {
public static double calculateArea(double radius) {
return Math.PI * radius * radius;
}
}
Then weβll create unit tests for the Circle class to make sure the calculateArea method works as expected.
Letβs create the CalculatorTest class in the src/main/test directory:
public class CircleTest {
@Test
public void testCalculateArea() {
//...
}
}
In this case, weβre using JUnitβs @Test annotation along with build tools such as Maven or Gradle to run the test.
3. Best Practices
3.1. Source Code
Itβs a good idea to keep the test classes separate from the main source code. So, they are developed, executed and maintained separately from the production code.
Also, it avoids any possibility of running test code in the production environment.
We can follow the steps of the build tools such as Maven and Gradle that look for src/main/test directory for test implementations.
3.2. Package Naming Convention
We should create a similar package structure in the src/main/test directory for test classes, this way improving the readability and maintainability of the test code.
Simply put, the package of the test class should match the package of the source class whose unit of source code itβll test.
For instance, if our Circle class exists in the com.baeldung.math package, the CircleTest class should also exist in the com.baeldung.math package under the src/main/test directory structure.
3.3. Test Case Naming Convention
The test names should be insightful, and users should understand the behavior and expectation of the test by just glancing at the name itself.
For example, the name of our unit test was testCalculateArea, which is vague on any meaningful information about the test scenario and expectation.
Therefore, we should name a test with the action and expectation such as testCalculateAreaWithGeneralDoubleValueRadiusThatReturnsAreaInDouble, testCalculateAreaWithLargeDoubleValueRadiusThatReturnsAreaAsInfinity.
However, we can still improve the names for better readability.
Itβs often helpful to name the test cases in given_when_then to elaborate on the purpose of a unit test:
public class CircleTest {
//...
@Test
public void givenRadius_whenCalculateArea_thenReturnArea() {
//...
}
@Test
public void givenDoubleMaxValueAsRadius_whenCalculateArea_thenReturnAreaAsInfinity() {
//...
}
}
We should also describe code blocks in the Given, When and Then format. In addition, it helps to differentiate the test into three parts: input, action and output.
First, the code block corresponding to the given section creates the test objects, mocks the data and arranges input.
Next, the code block for the when section represents a specific action or test scenario.
Likewise, the then section points out the output of the code, which is verified against the expected result using assertions.
3.4. Expected vs Actual
A test case should have an assertion between expected and actual values.
To corroborate the idea of the expected vs actual values, we can look at the definition of the assertEquals method of JUnitβs Assert class:
public static void assertEquals(Object expected, Object actual)
Letβs use the assertion in one of our test cases:
@Test
public void givenRadius_whenCalculateArea_thenReturnArea() {
double actualArea = Circle.calculateArea(1d);
double expectedArea = 3.141592653589793;
Assert.assertEquals(expectedArea, actualArea);
}
Itβs suggested to prefix the variable names with the actual and expected keyword to improve the readability of the test code.
3.5. Prefer Simple Test Case
In the previous test case, we can see that the expected value was hard-coded. This is done to avoid rewriting or reusing actual code implementation in the test case to get the expected value.
Itβs not encouraged to calculate the area of the circle to match against the return value of the calculateArea method:
@Test
public void givenRadius_whenCalculateArea_thenReturnArea() {
double actualArea = Circle.calculateArea(2d);
double expectedArea = 3.141592653589793 * 2 * 2;
Assert.assertEquals(expectedArea, actualArea);
}
In this assertion, weβre calculating both expected and actual values using similar logic, resulting in similar results forever. So, our test case wonβt have any value added to the unit testing of code.
Therefore, we should create a simple test case that asserts hard-coded expected value against the actual one.
Although itβs sometimes required to write the logic in the test case, we shouldnβt overdo it. Also, as commonly seen, we should never implement production logic in a test case to pass the assertions.
3.6. Appropriate Assertions
Always use proper assertions to verify the expected vs. actual results. We should use various methods available in the Assert class of JUnit or similar frameworks such as AssertJ.
For instance, weβve already used the Assert.assertEquals method for value assertion. Similarly, we can use assertNotEquals to check if the expected and actual values are not equal.
Other methods such as assertNotNull, assertTrue and assertNotSame are beneficial in distinct assertions.
3.7. Specific Unit Tests
Instead of adding multiple assertions to the same unit test, we should create separate test cases.
Of course, itβs sometimes tempting to verify multiple scenarios in the same test, but itβs a good idea to keep them separate. Then, in the case of test failures, itβll be easier to determine which specific scenario failed and, likewise, simpler to fix the code.
Therefore, always write a unit test to test a single specific scenario.
A unit test wonβt get overly complicated to understand. Moreover, itβll be easier to debug and maintain unit tests later.
3.8. Test Production Scenarios
Unit testing is more rewarding when we write tests considering real scenarios in mind.
Principally, it helps to make unit tests more relatable. Also, it proves essential in understanding the behavior of the code in certain production cases.
3.9. Mock External Services
Although unit tests concentrate on specific and smaller pieces of code, there is a chance that the code is dependent on external services for some logic.
Therefore, we should mock the external services and merely test the logic and execution of our code for varying scenarios.
We can use various frameworks such as Mockito, EasyMock and JMockit for mocking external services.
3.10. Avoid Code Redundancy
Create more and more helper functions to generate the commonly used objects and mock the data or external services for similar unit tests.
As with other recommendations, this enhances the readability and maintainability of the test code.
3.11. Annotations
Often, testing frameworks provide annotations for various purposes, for example, performing setup, executing code before and tearing down after running a test.
Various annotations such as JUnitβs @Before, @BeforeClass and @After and from other test frameworks such as TestNG are at our disposal.
We should leverage annotations to prepare the system for tests by creating data, arranging objects and dropping all of it after every test to keep test cases isolated from each other.
3.12. 80% Test Coverage
More test coverage for the source code is always beneficial. However, itβs not the only goal to achieve. We should make a well-informed decision and choose a better trade-off that works for our implementation, deadlines and the team.
As a rule of thumb, we should try to cover 80% of the code by unit tests.
Additionally, we can use tools such as JaCoCo and Cobertura along with Maven or Gradle to generate code coverage reports.
3.13. TDD Approach
Test-Driven Development (TDD) is the methodology where we create test cases before and in ongoing implementation. The approach couples with the process of designing and implementing the source code.
The benefit includes testable production code from the start, robust implementation with easy refactorings and fewer regressions.
3.14. Automation
We can improve the reliability of the code by automating the execution of the entire test suite while creating new builds.
Primarily, this helps to avoid unfortunate regressions in various release environments. It also ensures rapid feedback before a broken code is released.
Therefore, unit test execution should be part of CI-CD pipelines and alert the stakeholders in case of malfunctions.
4. Conclusion
In this article, we explored some best practices of Unit Testing in Java. Following best practices can help in many aspects of software development.
