Ambiguous Method Call Mocking RestTemplate.exchange()

前端 未结 2 1750
甜味超标
甜味超标 2021-01-22 21:45

Can\'t figure out the correct way to use matchers to identify which overload of the exchange method I am targetting. The call I am making:

restTemplate.exchange(ur

2条回答
  •  甜味超标
    2021-01-22 22:25

    I am not sure whether I misunderstood your question or the issue mentioned by @MarciejKowalski, but when running the test from the issue or what I suppose is similar to your example against mockito-core-2.23.4 / JDK 1.8.0_151 it works just fine.

    [I used JUnit 4 for your example instead of JUnit 5]

    import static org.mockito.ArgumentMatchers.any;
    
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.mockito.junit.MockitoJUnitRunner;
    import org.springframework.core.ParameterizedTypeReference;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.client.RestTemplate;
    
    @RunWith(MockitoJUnitRunner.class)
    public class MockitoTest {
    
        @Test
        public void test() {
    
            RestTemplate api = Mockito.mock(RestTemplate.class);
            ResponseEntity response1 = Mockito.mock(ResponseEntity.class);
            ResponseEntity response2 = Mockito.mock(ResponseEntity.class);
    
            Mockito.when(api.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class), any(Class.class))).thenReturn(response1);
            Mockito.when(api.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class), any(ParameterizedTypeReference.class))).thenReturn(response2);
    
            ParameterizedTypeReference mock = Mockito.mock(ParameterizedTypeReference.class);
    
            Assert.assertEquals(response1, api.exchange("", HttpMethod.GET, new HttpEntity(""), String.class));
            Assert.assertEquals(response2, api.exchange("", HttpMethod.GET, new HttpEntity(""), mock));
        }
    }
    

提交回复
热议问题