WebTestClient configured with wrong port

Viewed 726

I have written integration tests in Spock. Configured Spring boot context to random port. Documantation claims that then sprig should inject me properly configured WebTestClient instance however when i'm trying to make a call by those "autoconfigured instance I have error given below:

Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:8080
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    |_ checkpoint ⇢ Request to POST http://localhost:8080/sign-up [DefaultWebClient]

Here is my code: BaseIntegrationTest

@SpringBootTest(webEnvironment = RANDOM_PORT, classes= Application.class)
@ContextConfiguration
@EnableConfigurationProperties
abstract class BaseIntegrationSpec extends Specification {

Class using WebTestClient:

@Component
class WebTestClientWrapper {

    @Autowired
    private WebTestClient webTestClient

    @Autowired
    private ObjectMapper objectMapper
3 Answers

Make sure a server on localhost:8080 is already running when you start the test. WebTestClient assumes that an external server is running when it binds to server.

I encountered this error as well in my kotlin project and was able to solve this with the following configuration in my test directory.

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.test.web.reactive.server.WebTestClient

@Configuration
class TestConfiguration {

    @Autowired
    lateinit var appContext: ApplicationContext

    @Primary // <-- Is added because IntelliJ gave some warning that there are two beans
    @Bean
    fun createWebTestClient(): WebTestClient {

        return WebTestClient.bindToApplicationContext(appContext).build()
    }
}

Essentially I had to create the WebTestClient myself and bound it to the application context. Afterwards the dynamic port resolving worked as expected.

You can use the WebTestClient like you had before with @Autowire or constructor injection.

A possible solution is to annotate WebTestClientWrapper class with @Lazy if you use it directly in Test classes.

In this way, the WebTestClientWrapper bean creation will be delayed once it is needed - which will be in the Test class where the web server is already up and local.server.port is populated

Related