Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

Integration testing and Unit testin in Rest API

Integration testing

MockMvc is used in integration testing of Spring Boot applications to test HTTP endpoints in a simulated servlet environment. It allows you to:

  • Test the entire request-handling layer, including controllers, filters, and request/response processing, without starting the server.
  • Validate the actual HTTP status codes, headers, and JSON responses returned by your API.
@Test
void testVerifyCustomer() throws Exception {
    Customer customer = new Customer(
        1L, "John Doe", "Father Doe", "Mother Doe", "1990-01-01",
        "john.doe@example.com", "1234567890", true
    );

    Mockito.when(kycService.verifyCustomer(1L)).thenReturn(Optional.of(customer));

    mockMvc.perform(get("/kyc/verify/1"))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.customerId").value(1L))
           .andExpect(jsonPath("$.name").value("John Doe"))
           .andExpect(jsonPath("$.verified").value(true));
}

  
Here we are testing the behavior of the endpoint just like how it will work in the real world.

Unit Testing

In the case of unit test cases, we are verifying only the method output or the logic of the method.

We can say this involves isolated test cases by mocking the dependencies.

@Test
public void testSaveAlert() throws JsonProcessingException {
    // Arrange
    doNothing().when(notificationService).saveAlert(any(Alert.class));

    // Act
    ResponseEntity response = notificationController.saveNotification(alert);

    // Assert
    assertEquals(HttpStatus.CREATED, response.getStatusCode());
    assertEquals("Alert saved", response.getBody());
    verify(alertService, times(1)).saveAlert(any(Alert.class));
}

  
When to Use Integration Test: Use integration tests for testing the controller layer and HTTP-specific logic.
When to Use Unit Test: Use unit tests to validate small, isolated methods in your application.

Post a Comment

0 Comments