All posts

Testing Error Scenarios in Java Applications

Write effective Java error scenario tests with JUnit 5, Mockito exception simulation, Spring Boot test slices, and boundary condition coverage.

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 Free