🛠️

Enhancing API Testing with Assertions

Aug 16, 2024

Notes on API Testing and Assertions

Overview of the Lecture

  • Focus on enhancing test assertions for API endpoints.
  • Importance of thorough testing beyond just checking creation.

Key Points on Assertions

  • Current assertions are considered insufficient.
  • Need to validate the actual response from the API endpoint.
  • Use of mock MVC result handlers for testing.

Steps to Enhance Assertions

  1. Capture API Response

    • Utilize mock MVC result handlers to see what is returned from the API.
    • Example: print method can be used temporarily to check response body.
    • Expected response attributes: name and type of returned data.
  2. Implement Expect Statements

    • Use mockMvcResultMatchers.jsonPath to assert values in the response.
    • Example: expect(mockMvcResultMatchers.jsonPath("$.name").value(pokemonDto.getName()))
    • Validate that the attributes name and type match expected values.
  3. Testing the Whole Response

    • Create a test method for fetching all Pokemon.
    • Mock service method to return a response DTO.
    • Example of setup: when(pokemonService.getAllPokemon(pageSize, pageNumber)).thenReturn(responseDto);

Building the Test Method

  • Define the test method with proper annotations.
  • Use a builder pattern to create response DTOs.
  • Example: PokemonResponseDTO response = PokemonResponseDTO.builder().pageSize(10).last(true).pageNumber(1).content(new ArrayList<>(pokemonDtos)).build();

Performing the API Call

  • Use mockMvc.perform(get(...)) to simulate the GET request.
  • Set request parameters (pageNumber and pageSize) and content type.
    • Ensure content type is set to application/json.

Validating the Response

  • Expect response status to be OK.
  • Key focus on the content size of the response DTO.
  • Use JSON path helpers to verify content size.

Error Handling

  • Ensure proper constructors are added to models to avoid errors during tests.
  • Utilize no-args constructors as necessary.

Conclusion

  • Importance of comprehensive testing for API responses.
  • Encouragement to engage with content by liking and subscribing.