1

I'm trying to mock the WebClient in one of my tests. I found some examples online where people do the same.

One example from spring-data-elasticsearch and another one from some tutorials.

Here is my own example.

@Test
public void mytest() {
  WebClient webClient = mock(WebClient.class);
  RequestHeadersUriSpec headersUriSpec = mock(RequestHeadersUriSpec.class);
  when(webClient.get()).thenReturn(headersUriSpec);
}

Unfortunately I see some warnings. Here is what I got:

WebClient.RequestHeadersUriSpec is a raw type. References to generic type WebClient.RequestHeadersUriSpec should be parameterized

When I change my code and add a wildcard to the RequestHeadersUriSpec I get another error message.

@Test
public void mytest() {
  WebClient webClient = mock(WebClient.class);
  RequestHeadersUriSpec<?> headersUriSpec = mock(RequestHeadersUriSpec.class);
  when(webClient.get()).thenReturn(headersUriSpec);
}

The method thenReturn(WebClient.RequestHeadersUriSpec<capture#1-of ?>) in the type OngoingStubbing<WebClient.RequestHeadersUriSpec<capture#1-of ?>> is not applicable for the arguments (WebClient.RequestHeadersUriSpec<capture#3-of ?>)

If I let Java infer the type I'm getting a third message.

@Test
public void mytest() {
  WebClient webClient = mock(WebClient.class);
  var headersUriSpec = mock(RequestHeadersUriSpec.class);
  when(webClient.get()).thenReturn(headersUriSpec);
}

Type safety: The expression of type WebClient.RequestHeadersUriSpec needs unchecked conversion to conform to WebClient.RequestHeadersUriSpec<capture#1-of ?>

Now I'm wondering

  1. Why does it work for the other projects?
  2. How can I solve my problem?

Thank you very much!

Best regards, Mirco

zemirco
  • 16,171
  • 8
  • 62
  • 96
  • Can you update the versions you are using for Spring webclient & Mockito? – Nagaraj Tantri Apr 21 '21 at 09:21
  • We're already using the latest versions. – zemirco Apr 21 '21 at 10:59
  • The `WebClient.RequestHeadersUriSpec is a raw type` Warning is also coming in `spring-data-elasticsearch` repo and considering its a warning, there wouldn't have been any failure because of warnings. While those error for wildcard are valid because of the Mockito and you can find similar answers: https://stackoverflow.com/questions/7366237/mockito-stubbing-methods-that-return-type-with-bounded-wild-cards and https://stackoverflow.com/questions/15942880/mocking-a-method-that-return-generics-with-wildcard-using-mockito – Nagaraj Tantri Apr 21 '21 at 11:57

1 Answers1

0

Could you try with requestHeadersUriSpecMock and webClient defined like this:

    @Mock
    private WebClient webClientMock;
    
    @SuppressWarnings("rawtypes")
    @Mock
    private WebClient.RequestHeadersUriSpec requestHeadersUriSpecMock;

and then call, more or less as you wanted: when(webClientMock.get()).thenReturn(requestHeadersUriSpecMock);

Does that help and is that something acceptable for you? :)

devaga
  • 326
  • 2
  • 15