🌟 Day 16 of #100DaysOfCode: Mastering SpringBoot Integration Testing 🌟

Hey Invaders! 👽

#100DaysOfCode day 16: I finished section 11: SpringBoot (Part 2) All Layers. Today, I expanded my skills in integration testing within SpringBoot applications, particularly focusing on scenarios requiring JWT authentication for user login processes. I also explored the strategic use of the @Order annotation to control the execution order of tests and learned more about comprehensive testing across all layers.

Key Concepts Explored:

  • JWT Authentication Testing: Learned how to handle security in tests by simulating user authentication and verifying JWT token generation.

  • Use of @Order Annotation: Implemented ordered testing to manage dependencies between tests, which is crucial when outcomes are state-dependent.

Example Code:

Here's how I set up and executed the integration tests:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class UsersControllerIntegrationTest {

    @Value("${server.port}")
    private int serverPort;

    @LocalServerPort
    private int localServerPort;

    @Autowired
    private TestRestTemplate testRestTemplate;

    private String authorizationToken;

    @Test
    @Order(3)
    @DisplayName("/login works")
    void testUserLogin_whenValidCredentialsProvided_returnsJWTinAuthorizationHeader() throws JSONException {
        // Arrange
        JSONObject loginCreds = new JSONObject();
        loginCreds.put("email", "[email protected]");
        loginCreds.put("password", "12345678");

        HttpEntity<String> request = new HttpEntity<>(loginCreds.toString());

        // Act
        ResponseEntity response = testRestTemplate.postForEntity("/users/login", request, null);
        authorizationToken = response.getHeaders().getValuesAsList(SecurityConstants.HEADER_STRING).get(0);

        // Assert
        assertEquals(HttpStatus.OK, response.getStatusCode(), "HTTP status code should be 200");
        assertNotNull(authorizationToken, "Response should contain an authorization token");
        assertNotNull(response.getHeaders().getValuesAsList("UserId").get(0), "Response should contain UserId");
    }
}

What I Learned:

  • Configuring Test Environment: The use of @SpringBootTest with WebEnvironment.RANDOM_PORT to avoid port conflicts during tests.

  • Securing Test HTTP Requests: Demonstrated handling JWT in tests, ensuring secured endpoints are tested under authentication.

  • Detailed Assertions: Ensured that the tests not only check for successful login but also validate the presence of crucial headers in the response.

This approach to testing not only ensures that my application's authentication mechanisms are robust but also that the application behaves as expected under various scenarios, enhancing reliability and security.

You can check out my github to make more sense of how I used the @Order annotation!

Reply

or to participate.