简体   繁体   中英

How mock RestTemplate.exchange()?

I have tried almost everything but I keep getting a org.mockito.exceptions.misusing.PotentialStubbingProblem when trying to mock RestTemplate.exchange

Here is what I am trying to do:

@Test
    void headerTest() {
    var request = getRequest();

    when(restTemplate.exchange(
            ArgumentMatchers.any(),
            ArgumentMatchers.eq(HttpMethod.POST),
            ArgumentMatchers.<HttpEntity<MultiValueMap<String,Object>>>any(),
            ArgumentMatchers.<Class<String>>any())
    )
            .thenReturn(ResponseEntity.ok("{\"access_token\":\"token\"}"));

    client.getResponse(request,
            "HI");

    assertEquals(1,request.hashCode());
}

I have tried everything but I keep getting the following error:

org.mockito.exceptions.misusing.PotentialStubbingProblem: 
Strict stubbing argument mismatch. Please check:
 - this invocation of 'exchange' method:
    restTemplate.exchange(
    null,
    POST,
    <{grant_type=[client_credentials]},[AUTHORIZATION:"Basic ", Content-Type:"application/x-www-form-urlencoded"]>,
    class java.lang.String
);
    -> at com.client.Client.getToken(WeightedAverageCostClient.java:148)
 - has following stubbing(s) with different arguments:
    1. restTemplate.exchange(
    null,
    null,
    null,
    null
);

Using lenient() I am getting a response of NULL.

What am I doing wrong?

This is what worked for me:

when(restTemplate.exchange(
                ArgumentMatchers.any(),
                ArgumentMatchers.eq(HttpMethod.POST),
                ArgumentMatchers.<HttpEntity<MultiValueMap<String, Object>>>any(),
                ArgumentMatchers.<Class<String>>any(),
                (Object) any())
        )
                .thenReturn(ResponseEntity.ok("{\"access_token\":\"token\"}"));

What is the reason to mock the restTemplate itself? The generic recommendation is to avoid the restTemplate invocation at all by using fake services.

In case of the invocation is absolutely mandatory the in-memory stub solution like mock-server could be used during the tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM