Write testable code using dependency injection to enable loose coupling, as seen by replacing hard-coded dependencies with injected ones; 2. Use JUnit 5 for structured testing with features like @BeforeEach, @Test, and assertThrows to ensure clean, readable, and reliable tests; 3. Mock external dependencies with Mockito using mock(), when().thenReturn(), and verify() to isolate behavior and avoid reliance on real systems; 4. Follow best practices such as descriptive test names, the AAA pattern, avoiding implementation detail tests, keeping tests independent, not over-mocking, and covering edge cases to ensure maintainable and effective tests; ultimately, designing for testability improves code quality, making it easier to change, debug, and trust.
Writing testable Java code is a critical skill for building maintainable, robust applications. With JUnit 5 as the modern testing framework and Mockito for mocking dependencies, you can write clean, reliable unit tests that verify behavior without relying on external systems. Here’s how to structure your code and tests effectively.

1. Write Testable Code: Dependency Injection and Loose Coupling
The foundation of testable code is dependency injection (DI) and loose coupling. Avoid hard-coded dependencies or static calls that make testing difficult.
Bad example (hard to test):

public class OrderService { private EmailService emailService = new EmailService(); // Hard dependency public void process(Order order) { // logic emailService.sendConfirmation(order); } }
This tightly couples OrderService
to EmailService
, making it impossible to test process()
without actually sending emails.
Good approach (testable with DI):

public class OrderService { private final EmailService emailService; public OrderService(EmailService emailService) { this.emailService = emailService; } public void process(Order order) { // business logic emailService.sendConfirmation(order); } }
Now you can inject a mocked EmailService
during testing using Mockito.
2. Use JUnit 5 for Structured, Readable Tests
JUnit 5 offers a modern syntax with improved lifecycle management and expressive assertions.
Example test class:
import org.junit.jupiter.api.*; import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; @TestInstance(TestInstance.Lifecycle.PER_METHOD) class OrderServiceTest { private EmailService emailService; private OrderService orderService; @BeforeEach void setUp() { emailService = mock(EmailService.class); orderService = new OrderService(emailService); } @Test @DisplayName("Should send confirmation email when processing order") void shouldSendEmailOnProcess() { // Given Order order = new Order("123", 100.0); // When orderService.process(order); // Then verify(emailService, times(1)).sendConfirmation(order); } @Test @DisplayName("Should throw exception for null order") void shouldThrowExceptionForNullOrder() { // When & Then assertThrows(IllegalArgumentException.class, () -> { orderService.process(null); }); } }
Key JUnit 5 features used:
@BeforeEach
– runs before each test (clean state)@Test
– marks test methods@DisplayName
– improves readability in test reportsassertThrows
– verifies expected exceptionsverify()
– checks interaction with mocks
3. Mock Dependencies with Mockito
Mockito allows you to simulate external services (e.g., databases, APIs, email) so your unit tests run fast and isolate behavior.
Common Mockito patterns:
- Mock creation:
mock(ClassName.class)
- Stubbing methods:
when(mock.method()).thenReturn(value)
- Verifying interactions:
verify(mock).method()
Example: Stubbing a repository call
public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public User findUserById(String id) { return userRepository.findById(id) .orElseThrow(() -> new UserNotFoundException("User not found")); } }
Test with Mockito:
@Test @DisplayName("Should return user when found in repository") void shouldReturnUserWhenFound() { // Given UserRepository userRepository = mock(UserRepository.class); User mockUser = new User("1", "Alice"); when(userRepository.findById("1")).thenReturn(Optional.of(mockUser)); UserService userService = new UserService(userRepository); // When User result = userService.findUserById("1"); // Then assertEquals("Alice", result.getName()); verify(userRepository).findById("1"); }
You’re testing only the logic in UserService
, not the real database.
4. Best Practices for Clean, Maintainable Tests
Follow these guidelines to keep your tests effective:
Use descriptive test names
PrefershouldThrowExceptionWhenOrderIsNull()
overtestProcess()
.Follow AAA pattern
Organize tests into Arrange, Act, Assert blocks for clarity.Avoid testing implementation details
Test what the method does, not how it does it. Don’t verify internal private methods.Keep tests independent and fast
No shared state between tests. Use@BeforeEach
or factory methods instead.Don’t over-mock
Only mock external dependencies. Don’t mock value objects or simple utilities.Test edge cases
Null inputs, empty collections, exceptions – these are common failure points.
Final Thoughts
Writing testable Java code isn’t just about adding tests—it’s about designing your classes with testability in mind. Use dependency injection, favor composition over instantiation, and separate concerns cleanly.
With JUnit 5 and Mockito, you get powerful tools to:
- Write expressive, readable tests
- Isolate units of behavior
- Simulate dependencies safely
The result? Code that’s easier to change, debug, and trust.
Basically, if you can’t test it easily, rethink the design.
The above is the detailed content of Writing Testable Java Code with JUnit 5 and Mockito. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Mockito framework annotations simplify the stub generation and verification process: @Mock: automatically generate and manage mock objects. @Captor: Capture the parameter value passed to the mock method. @InjectMocks: Automatically inject mock objects into the class under test. @Spy: Create some stub objects and retain the original method implementation.

With the popularity of the Internet, Java back-end development has become an important field. In the development process, unit testing is a very critical step, and Mockito is an excellent API unit test simulation tool. This article will introduce how to use Mockito in Java back-end development. What is Mockito? Mockito is a Java framework that provides API unit testing simulation capabilities in the form of Mock objects. Mock objects refer to some virtual objects whose behavior is set by us

Introduction RESTful APIs are becoming increasingly popular, so ensuring their robustness becomes critical. Unit testing is an effective way to verify the functionality and behavior of your code, especially for RESTful APIs. This article explains how to use JAX-RS and unit testing frameworks such as Mockito and RESTAssured to test RESTful code. Introduction to JAX-RS JAX-RS is a Java API for building RESTful APIs. It provides a set of annotations and classes for defining resources and handling HTTP requests and responses. Using JAX-RS, developers can easily create RESTful services that can communicate with a variety of clients. unit test

Introduction to Mockito When calling the method of a mock object, the real method will not be executed, but the default value of the return type, such as object returns null, int returns 0, etc. Otherwise, the method is specified by specifying when(method).thenReturn(value) return value. At the same time, the mock object can be tracked and the verify method can be used to see whether it has been called. The spy object will execute the real method by default, and the return value can be overridden through when.thenReturn. It can be seen that as long as mock avoids executing some methods and directly returns the specified value, it is convenient for other tests. Service test cases require dependencies junitjunit4.1

Mockito and JUnit join forces to improve unit testing efficiency: Mockito allows the creation of test stubs and mock objects to verify the expected interactions of the code. JUnit provides a framework to make test writing and running easier. When used together, you can create highly readable and maintainable tests that effectively verify the correctness of your code.

Steps to test Java functions using Mockito: Add Mockito dependencies. Create mock objects and set mock behavior. Call the function to be tested. Assert the expected behavior of a function. Use verify() to verify simulated interactions.

As software development continues to advance, test-driven development (TDD) has become an increasingly popular development model. In the process of TDD, testing becomes the core of the development process, and JUnit and Mockito are two commonly used testing frameworks. In PHP development, how to use JUnit and Mockito for TDD? A detailed introduction will be given below. 1. Introduction to JUnit and Mockito JUnit is a testing framework for the Java language. It can help Java

Introduction JUnit is an open source framework for unit testing of Java code, founded in 1997 by Erich Gamma and Kent Beck. It allows developers to write test cases that verify the correctness of the code. Through unit testing, developers can ensure that the code works as expected at the individual unit level, thereby improving the robustness and reliability of the code. Basic Usage A JUnit test case is a method annotated with @Test, which usually starts with test. It contains the following parts: Setup: In the @Before method, set the necessary status for each test case. Test: In the @Test method, execute the logic to be tested and verify the results. Cleanup: In @After method, in each test case
