Testing
01 What is @SpringBootTest and when should it be used?
Solution and explanation
- Solution:
- Testing should happen at different levels.
- Unit test:
- Tests one class.
- Example:
- JobService
- Integration test:
- Tests several real Spring components.
- Example:
- Controller
- Service
- Repository
- Database
- @SpringBootTest:
- Loads the Spring Boot application context.
- This is useful when we want to verify that the actual application wiring works.
- Example:
- POST /api/jobs
- Request enters:
- Controller
- |
- Service
- |
- Repository
- |
- Database
- A broad integration test can verify the complete flow.
- However, using @SpringBootTest for every small test can make the test suite slow.
- Use unit tests for isolated business logic and integration tests for important interactions.
@SpringBootTest
@ActiveProfiles("test")
class JobApplicationFlowTest {
@Autowired
private MockMvc mockMvc;
@Test
void candidateCanApplyForOpenJob()
throws Exception {
mockMvc.perform(
post("/api/jobs/100/applications")
.contentType("application/json")
.content("""
{
"candidateId": 50
}
""")
)
.andExpect(status().isCreated());
}
}
Create one complete application-flow integration test and separate it from unit tests.
Quick check
Which statement is correct?
02 What is MockMvc?
Solution and explanation
Solution:
MockMvc allows testing Spring MVC endpoints without starting a real external web server.
Suppose:
GET /api/jobs
The test can verify:
- HTTP status
- JSON structure
- headers
- authentication
- validation
- controller behavior
Example:
Expected:
200 OK
and:
content = array
For validation:
POST /api/jobs
with missing title.
Expected:
400 Bad Request
For unauthorized access:
DELETE /api/jobs/100
Expected:
401 or 403 depending on authentication state and authorization rules.
MockMvc is therefore useful for testing the HTTP/controller layer.
mockMvc.perform(
get("/api/jobs")
.param("location", "Ludhiana")
.param("page", "0")
)
.andExpect(status().isOk())
.andExpect(
jsonPath("$.content").isArray()
);
mockMvc.perform(
post("/api/jobs")
.contentType("application/json")
.content("""
{
"title": ""
}
""")
)
.andExpect(status().isBadRequest());
Test successful job search, invalid job creation and unauthorized access using MockMvc.
Quick check
Which statement is correct?
