Spring Boot Testing - Integration tests for the Controller
Table of Contents
Integration tests for the Controller
See
- https://github.com/explorer436/programming-playground/tree/main/java-playground/testing-examples
- https://github.com/explorer436/programming-playground/tree/main/java-playground/request-logging
Start the application. And then send an HTTP request and assert the response.
Start the application and listen for a connection (as it would do in production) and then send an HTTP request and assert the response.
webEnvironment=RANDOM_PORT
starts the server with a random port (useful to avoid conflicts in test environments).
The port is injected with @LocalServerPort
.
Spring Boot automatically provides a TestRestTemplate
for you. All you have to do is add @Autowired
to it.
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void greetingShouldReturnDefaultMessage() throws Exception {
assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/",
String.class)).contains("Hello, World");
}
}
Reference
https://spring.io/guides/gs/testing-web