Search code examples
spring-bootkotlinunit-testingmockitowebclient

Is there a way to mock Webclient post call with mockito


I want to mock a webclient post call using Mockito. But when mocking the post call I get a null pointer exception with the stacktrace:

Cannot invoke "org.springframework.web.reactive.function.client.WebClient$RequestBodyUriSpec.uri(String, Object[])" because the return value of "org.springframework.web.reactive.function.client.WebClient.post()" is null

My code


@ActiveProfiles("unit-test")
@SpringBootTest
class ServiceTest {
   @MockBean
   lateinit var mockWebClient: WebClient
   
   @Test
   fun webclientMockedTest() {
       `when`(mockWebClient.post().uri("/path").body(Mono.just(request), request::class.java)
        .retrieve().bodyToMono(response::class.java).block())
        .thenReturn(response)
   }
}

I was trying to mock webclient post call with the request and response DTO, however I am getting NPE. I am using mock.mockito.MockBean and Mockito.when library


Solution

  • I was able to mock the webclient using the following method which takes uri, requestDTO, responseDTO as input and return and mock webclient.

    fun createMockWebClient(uri: String, requestDTO: Any, responseDTO: Any): WebClient {
            // Create the mock objects
            val mockWebClient = mock(WebClient::class.java)
            val requestBodyUriMock = mock(WebClient.RequestBodyUriSpec::class.java)
            val requestBodyMock = mock(WebClient.RequestBodySpec::class.java)
            val requestHeadersMock = mock(WebClient.RequestHeadersSpec::class.java)
            val responseSpecMock = mock(WebClient.ResponseSpec::class.java)
            val responseMock = mock(ClientResponse::class.java)
    
            // Configure the mock objects
            `when`(mockWebClient.post()).thenReturn(requestBodyUriMock)
            `when`(requestBodyUriMock.uri(uri)).thenReturn(requestBodyMock)
            `when`(requestBodyMock.bodyValue(requestDTO)).thenReturn(requestHeadersMock)
            `when`(requestHeadersMock.retrieve()).thenReturn(responseSpecMock)
            `when`(responseSpecMock.bodyToMono(any(Class::class.java))).thenReturn(Mono.just(responseDTO))
            `when`(responseMock.bodyToMono(any(Class::class.java))).thenReturn(Mono.just(responseDTO))
    
            return mockWebClient
        }