Issue
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
Solution
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.
Answered By - SimonH
Answer Checked By - Terry (JavaFixing Volunteer)