Testing Error Scenarios in Java Applications
Robust Java applications need thorough error scenario testing. Here's how to test failure paths effectively with JUnit 5 and Mockito.
Assert Exceptions with JUnit 5
@Test
void getUser_withInvalidId_throwsNotFoundException() {
assertThrows(ResourceNotFoundException.class, () -> {
userService.getUser("nonexistent-id");
});
}
@Test
void getUser_withInvalidId_hasCorrectMessage() {
var exception = assertThrows(ResourceNotFoundException.class, () -> {
userService.getUser("invalid");
});
assertEquals("User with id invalid not found", exception.getMessage());
}Simulate Failures with Mockito
@Test
void createOrder_whenDatabaseFails_throwsServiceException() {
when(orderRepository.save(any(Order.class)))
.thenThrow(new DataAccessException("Connection refused") {});
assertThrows(ServiceException.class, () -> {
orderService.createOrder(validOrderRequest);
});
}
@Test
void fetchData_whenServiceTimesOut_returnsDefault() {
when(externalClient.getData(anyString()))
.thenThrow(new SocketTimeoutException("Read timed out"));
var result = dataService.fetchWithFallback("key");
assertEquals(DataService.DEFAULT_VALUE, result);
}Spring Boot Controller Error Tests
@WebMvcTest(UserController.class)
class UserControllerErrorTest {
@Autowired MockMvc mockMvc;
@MockBean UserService userService;
@Test
void getUser_notFound_returns404() throws Exception {
when(userService.getUser("123"))
.thenThrow(new ResourceNotFoundException("User", "123"));
mockMvc.perform(get("/api/users/123"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.errorCode").value("RESOURCE_NOT_FOUND"));
}
@Test
void createUser_invalidBody_returns400() throws Exception {
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isBadRequest());
}
}Error Scenarios to Cover
- Null and empty inputs — boundary conditions
- Concurrent modification — OptimisticLockException handling
- External service failures — timeouts, connection refused
- Data integrity violations — duplicate key, constraint violations
- Authentication and authorization failures — expired tokens, missing roles
Complement your test suite with Bugsly's production error tracking. Every unhandled exception Bugsly catches should become a new test case in your suite.
Try Bugsly Free
AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.
Get Started FreeRelated Articles
Deno Error Tracking: A Complete Setup Guide
Learn how to set up error tracking in Deno with Bugsly. Step-by-step guide with code examples and best practices.
Read moreSpring Boot CI/CD Monitoring: Complete Setup Guide
Learn how to set up ci/cd monitoring in Spring Boot with Bugsly. Step-by-step guide with code examples and best practices.
Read moreBuilding a React Application Monitoring Dashboard
Set up a React monitoring dashboard tracking Core Web Vitals, error rates, API performance, and user experience metrics in real-time.
Read moreFastAPI CI/CD Monitoring: Complete Setup Guide
Set up ci/cd monitoring for FastAPI using Bugsly. Quick installation, configuration, and verification steps included.
Read more