Integration testing

When we do integration testing, we would want to launch the embedded server with all the controllers and beans that are configured. This code snippet shows how we can create a simple integration test:

    @RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BasicControllerIT {

private static final String LOCAL_HOST =
"http://localhost:";

@LocalServerPort
private int port;

private TestRestTemplate template = new TestRestTemplate();

@Test
public void welcome() throws Exception {
ResponseEntity<String> response = template
.getForEntity(createURL("/welcome"), String.class);
assertThat(response.getBody(), equalTo("Hello World"));
}

private String createURL(String uri) {
return LOCAL_HOST + port + uri;
}
}

A few important things to note are as follows:

  • @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT): Provides additional functionality on top of the Spring TestContext. Provides support to configure the port for fully running the container and TestRestTemplate (to execute requests).
  • @LocalServerPort private int port: SpringBootTest would ensure that the port on which the container is running is autowired into the port variable.
  • private String createURL(String uri): The method to append the local host URL and port to the URI to create a full URL.
  • private TestRestTemplate template = new TestRestTemplate(): TestRestTemplate is typically used in integration tests. It provides additional functionality on top of RestTemplate, which is especially useful in the integration test context. It does not follow redirects so that we can assert response location.
  • template.getForEntity(createURL("/welcome"), String.class): Executes a get request for the given URI.
  • assertThat(response.getBody(), equalTo("Hello World")): Asserts that the response body content is "Hello World".
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset