Best Practices for Unit Testing in Java

announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Bellsoft – NPI EA (cat = JVM)

announcement - icon

Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.

To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).

These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:

Partner – Orkes – NPI EA (tag=Microservices)

announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Partner – Microsoft – NPI EA (cat= Spring Boot)

announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Jmix-Haulmont – NPI EA (cat= Spring Boot)

announcement - icon

Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.

Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.

Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin, and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.

The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:

Partner – DBSchema – NPI EA (tag = Spring Data JPA)

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Partner – Codium – NPI EA (cat = Testing)

announcement - icon

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

Partner – Machinet – NPI EA (cat = Testing)

announcement - icon

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation.
Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.
And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI:

Partner – DBSchema – NPI EA (tag = SQL)

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

eBook – Java Streams – NPI EA (cat=Java Streams)

announcement - icon

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:

eBook – Jackson – NPI EA (cat=Jackson)

announcement - icon

Do JSON right with Jackson

eBook – HTTP Client – NPI EA (cat=Http Client-Side)

announcement - icon

Get the most out of the Apache HTTP Client

eBook – Maven – NPI EA (cat = Maven)

announcement - icon

Get Started with Apache Maven:

eBook – Persistence – NPI EA (cat=Persistence)

announcement - icon

Working on getting your persistence layer right with Spring?

eBook – RwS – NPI EA (cat=Spring MVC)

announcement - icon

Building a REST API with Spring?

Course – LS – NPI EA (cat=Jackson)

announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

Course – RWSB – NPI EA (cat=REST)

announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

Course – LS – NPI EA (cat=Spring)

announcement - icon

Get started with Spring and Spring Boot, through the reference Learn Spring course:

Course – LSS – NPI EA (cat=Spring Security)

announcement - icon

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:

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()

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()

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.

Partner – DBSchema – NPI EA (tag = SQL)

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Baeldung Pro – NPI EA (cat = Baeldung)

announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (tag = Microservices)

announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Partner – Microsoft – NPI EA (cat = Spring Boot)

announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Machinet – NPI EA (cat = Baeldung)

announcement - icon

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation.
Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.
And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI:

Partner – DBSchema – NPI EA (tag = Spring Data JPA)

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Partner – Bellsoft – NPI EA (cat = Spring)

announcement - icon

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux: lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps. It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

Partner – Codium – NPI EA (cat = Testing)

announcement - icon

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

Partner – Machinet – NPI EA (cat = Testing)

announcement - icon

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation.
Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Simplify Your Coding Journey with Machinet AI:

Course – LS – NPI EA (cat=REST)


announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course: