Master Spring Boot Unit Testing with MockMvc: A Complete Guide
This article explains the fundamentals of unit testing in Spring Boot, covering the purpose of unit tests, how to add the spring-boot-starter-test dependency, the role of MockMvc for controller testing, step‑by‑step creation of Service and Controller test classes, key annotations, assertion techniques, and a brief comparison with Postman.
1. Unit Testing Concept
Unit testing refers to checking and validating the smallest testable units in software; in Java the smallest unit is a class. It is a small piece of code written by developers to verify that a specific, well‑defined functionality works as expected.
Unit testing (unit testing) is the verification of the smallest testable component in software; in Java the smallest unit is a class.
It is a short piece of code that checks whether a tiny, precise function behaves as expected.
The Spring Boot project created via spring initialize automatically includes many starter dependencies, among them spring-boot-starter-test, which this guide focuses on.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>spring-boot-starter-test includes several libraries (UML diagram omitted).
2. Purpose of Unit Testing
Before using unit tests, developers typically rely on manual testing or ad‑hoc scripts. Writing unit tests saves time, ensures code correctness, and protects existing functionality from regression.
Two main motivations for writing unit tests:
Verify that implemented functionality works correctly.
Prevent already‑implemented functionality from being broken.
3. MockMvc Concept in Spring Boot
What is a Mock?
Why use mock objects?
MockMvc concept.
A mock object simulates the behavior of a real object in a controllable way, allowing tests to verify program outcomes without relying on the actual implementation.
MockMvc, provided by the spring-test package, simulates HTTP requests, enabling fast controller testing without a running server and offering convenient result verification tools.
The MockMvcBuilder interface provides a single build method; its two main implementations are StandaloneMockMvcBuilder and DefaultMockMvcBuilder.
4. Service Layer Unit Testing
Step 1: Create a test class under src/test/java. IDEs like IntelliJ IDEA can generate the class automatically.
Step 2: After clicking “Create New Test…”, a dialog appears where you can choose to generate setUp methods and select which member methods to test.
Step 3: The generated test class is placed alongside the source code in src/test/java.
Example Service layer test code:
@SpringBootTest
@RunWith(SpringRunner.class)
public class XXXServiceTest {
@Resource
private XXXService XXXService;
@Test
public void conflictTime() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate start = LocalDate.parse("2020-10-26", dtf);
LocalDate end = LocalDate.parse("2020-10-31", dtf);
Integer integer = XXXService.ConflictTime("10000001", start, end);
Assert.assertThat(integer, Matchers.notNullValue());
}
}Key annotations: @SpringBootTest: loads the main configuration class annotated with @SpringBootApplication. @RunWith(SpringRunner.class): runs tests with Spring’s testing support.
5. Controller Layer Unit Testing
Testing the controller (API) layer also uses MockMvc, allowing you to test endpoints without starting the full application.
Example test class snippet:
@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class DfTaskRecordControllerTest {
@Autowired
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
System.out.println("---------------start---------------");
save();
get();
System.out.println("================end================");
}
}Important annotations: @AutoConfigureMockMvc: automatically configures MockMvc for injection. @Before: runs before each test method.
6. Assertion Concept
An assertion is a boolean expression that the programmer expects to be true at a specific point in the program.
Assertions are used to verify that a function or method produces the expected result.
7. Using assertThat with Hamcrest
JUnit 4.4 combined with Hamcrest introduces assertThat, which can replace all traditional JUnit assertions and provides readable, flexible matcher syntax.
Advantages:
One method ( assertThat) replaces multiple assertion methods, simplifying test code.
Hamcrest matchers allow precise condition specification, improving readability.
The syntax follows a “subject‑verb‑object” style, e.g., assertThat(x, is(3)), making tests more intuitive.
assertThat( [value], [matcher statement] );8. Postman vs Spring Boot Unit Testing
Spring Boot unit tests focus on method‑level verification, can test Service layer logic, support batch testing and transaction rollback.
Postman performs HTTP‑level testing of APIs, allowing you to save and organize test requests.
9. Basic Postman Usage
Postman is a powerful tool for sending HTTP requests (GET, POST, PUT, etc.) with parameters and headers, supporting various authentication methods and response syntax highlighting.
Official download site: https://www.getpostman.com/apps
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
