I am writing integration tests in spock framework for spring web flux application and we are using WebClient to make external api call. How can I mock WebClient and stub data to WebClient calls?
I am using RequestSpecification class to make api calls in integration tests.
I was able to resolve this problem by using below code:
WebClient webClient
WebClient.RequestBodyUriSpec requestBodyUriSpec =
Mock(WebClient.RequestBodyUriSpec)
WebClient.ResponseSpec responseSpec = Mock(WebClient.ResponseSpec)
inside test methods:
webClient.get() >> requestBodyUriSpec
webClient.post() >> requestBodyUriSpec
requestBodyUriSpec.body(_, _) >> requestBodyUriSpec
requestBodyUriSpec.uri(_) >> requestBodyUriSpec
requestBodyUriSpec.headers(_) >> requestBodyUriSpec
requestBodyUriSpec.retrieve() >> responseSpec
responseSpec.onStatus(_, _) >> responseSpec
responseSpec.bodyToMono(_) >>> {response objects to be mocked}