嘲笑resttemplate交换总是返回null

时间:2019-04-09 10:28:36

标签: spring junit mockito resttemplate argument-matcher

我正在尝试通过Mockito模拟restTemplate.exchange方法,但无论我通过模拟返回什么,即使我抛出异常,它总是返回null值:

这是实际的代码:

ResponseEntity<List<LOV>> response = restTemplate.exchange(url, GET, null,new ParameterizedTypeReference<List<LOV>>() {});

mockito代码:

 ResponseEntity<List<LOV>> mockResponse = new ResponseEntity<List<LOV>>(mockLovList() ,HttpStatus.ACCEPTED);

Mockito.when(restTemplate.exchange(any(), eq(GET), any(), ArgumentMatchers.<ParameterizedTypeReference<List<LOV>>>any())).thenReturn(mockResponse);

在交换模拟中,每个参数的类型均为ArgumentMatchers, mockLovList()返回LOV列表

它应该返回我嘲笑的内容,但始终返回null

3 个答案:

答案 0 :(得分:1)

在设置或注入服务之前,您需要确保已初始化模拟。像这样-

@Mock
RestTemplate restTemplate;
@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    userData = new UserService(restTemplate);
}

答案 1 :(得分:0)

首先,您可以使用以下方法验证方法调用是否正确

 Mockito.verify(restTemplate).exchange(any(), eq(GET), any(), any(ParameterizedTypeReference.class)))

Mockito显示了非常好的输出,包括实际的方法调用。

此外,您可以参考Deep StubbingTesting anonymous classes

答案 2 :(得分:0)

这是RestTemplate.exchange()模拟测试的有效示例:

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

import static org.mockito.Mockito.*;

public class MyTest {

    @Test
    public void testRestTemplateExchange() {
        RestTemplate restTemplate = mock(RestTemplate.class);

        HttpEntity<String> httpRequestEntity = new HttpEntity<>("someString");

        List<String> list = Arrays.asList("1", "2");
        ResponseEntity mockResponse = new ResponseEntity<>(list, HttpStatus.ACCEPTED);
        when(restTemplate.exchange(anyString(), any(), any(), any(ParameterizedTypeReference.class), any(Object[].class)))
                .thenReturn(mockResponse);


        final ResponseEntity<List<String>> exchange = restTemplate.exchange("/someUrl", HttpMethod.GET, httpRequestEntity, new ParameterizedTypeReference<List<String>>() {
        });

        Assert.assertEquals(list, exchange.getBody());

    }

}