spring - mock resttemplate 交换总是返回 null

标签 spring junit mockito resttemplate argument-matcher

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

这是实际的代码:

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

模拟代码:
 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 列表

它应该返回我 mock 的任何东西,但它总是返回 null

最佳答案

这是一个 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());

    }

}

关于spring - mock resttemplate 交换总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590669/

相关文章:

java - 使用不同的事务属性调用 Spring Bean 的方法?

spring - 为什么我得到 "HTTP Status 404 - Servlet <servlet name> is not available"

Spring Security - 用于 Multi-Tenancy 应用程序的 OAuth、LDAP 集成

spring - Spring命令行JSON配置包含数组

java - Mockito - 验证一个方法是否调用同一类中的另一个方法

testing - 不运行 Tomcat 的 RestAssured 测试

java - 如何模拟 HTTP 响应

java - 无法模拟方法响应

windows - 在 Weblogic 中使用本地版本的 ANT 和 JUNIT 运行 ant build

java - 使用mockito调用Service类的嵌套方法时出现NullPointerException