Integration testing

When we integration testing, we will want to launch the embedded server with all the controllers and beans that are configured. The following block of code shows how we can create a simple integration test:

    @RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class BasicControllerIT {
@Autowired
lateinit var restTemplate: TestRestTemplate
@Test
fun `GET welcome returns "Hello World"`() {
// When
val body = restTemplate.getForObject("/welcome",
String::class.java)
// Then
assertThat(body).isEqualTo("Hello World")
}
}

A few important things to note are as follows:

  • @RunWith(SpringRunner::class), @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT): SpringBootTest provides additional functionality on top of the Spring TestContext. It provides support to configure the port for fully running container and TestRestTemplate (to execute requests). This is similar to the Java code, except for the class reference.
  • @Autowired lateinit var restTemplate: TestRestTemplate: TestRestTemplate is typically used in integration tests. It provides additional functionality on top of the RestTemplate, which is especially useful in the integration of the test context. It does not follow redirects so that we can assert the response location. lateinit allows us to avoid null checks for the autowired variables.
..................Content has been hidden....................

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