mocking resttemplate exchange总是返回null

问题描述 投票:0回答:2

我试图通过mockito模拟restTemplate.exchange方法,但无论我通过mock返回什么,它总是返回一个空值,即使我抛出异常:

这是实际的代码:

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

spring junit mockito resttemplate argument-matcher
2个回答
0
投票

首先,您可以使用确认方法调用是否正确

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

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

另外,你可以参考Deep StubbingTesting anonymous classes


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());

    }

}
© www.soinside.com 2019 - 2024. All rights reserved.