Idiomatic way of configuring integration tests in spring

Viewed 30

What is the idiomatic (and easiest) way of configuring integration tests in Spring?

For example let's define a sample integration test:

@ActiveProfiles("dev", "test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SampleTest() {

  @LocalServerPort
  lateinit var port: Number

  lateinit var client: WebTestClient

  @BeforeEach
  fun setup() {
    client = WebTestClient.bindToServer().baseUrl("http://localhost:$port").build()
  }

  @Test
  fun test() {
    client.get()
      .uri("/api/something")
      .exchange()
      .expectStatus().is2xxSuccessful
      .expectBody()
  }
}

There are many ways i can configure WebTestClient but I don't know which one is "the best". To name a few:

  • lateinit var and BeforeEach
  • configure in each test separately

Given my project's structure and conventions most of things we get from DI is injected via constructor using @Autowired annotation. Is it also possible in this case? Therefore i'd just do:

@ActiveProfiles("dev", "test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SampleTest(
 @Autowired val client: WebTestClient
) {
  @Test
  fun test() {
    client.get()
      .uri("/api/something")
      .exchange()
      .expectStatus().is2xxSuccessful
      .expectBody()
  }
}

I've tried to do it without other modifications and some of my tests fail because of connection refused

0 Answers
Related