我如何模拟 RestTemplate 交换 [英] How do i mock RestTemplate exchange

查看:80
本文介绍了我如何模拟 RestTemplate 交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试模拟如下:

Mockito.doReturn(responseEntity).when(restTemplate.exchange(anyString(), anyObject(), anyObject(), anyObject()));

这给了我一个编译问题:

this gave me a compilation issue:

方法 exchange(String, HttpMethod, HttpEntity, Class, Object[]) 对 RestTemplate 类型不明确"

"The method exchange(String, HttpMethod, HttpEntity, Class, Object[]) is ambiguous for the type RestTemplate"

尝试过:

GetRelationshipInfoResponse relationship = getEntity();
        ResponseEntity<GetRelationshipInfoResponse> responseEntity = new ResponseEntity<GetRelationshipInfoResponse>(relationship,
                HttpStatus.ACCEPTED);
        Mockito.doReturn(responseEntity).when(restTemplate.exchange(anyString(), Matchers.eq(HttpMethod.POST),
                Matchers.<HttpEntity<?>> any(), Matchers.<Class<Object>> any()));

我现在在运行时看到 MethodInterceptorFilter.intercept 正在获取空对象值.

I see in runtime now in MethodInterceptorFilter.intercept is getting null object value.

任何人都可以建议我如何修复.

Can anybody suggest how can I fix.

推荐答案

我曾经遇到过这样的错误.我想出了一个更可靠的解决方案.我也提到了对我有用的导入语句.下面这段代码完美地模拟了其余的模板.

I used to get such an error. I figured out a more reliable solution. I have mentioned the import statements too which have worked for me. The below piece of code perfectly mocks the rest template.

import org.mockito.Matchers; 
import static org.mockito.Matchers.any;  
import org.springframework.http.HttpHeaders;  
import org.springframework.http.ResponseEntity;

这是要模拟的实际模板.

This is the actual template to mock.

    HttpHeaders headers = new Headers();
    headers.setExpires(10000L);     
    ResponseEntity<String> responseEntity = new ResponseEntity<>("dummyString", headers, HttpStatus.OK);
    when(restTemplate.exchange( Matchers.anyString(), 
            Matchers.any(HttpMethod.class),
            Matchers.<HttpEntity<?>> any(), 
            Matchers.<Class<String>> any())).thenReturn(responseEntity);

这里的 'responseEntity' 值不会为空,我们可以用它来完美地断言一个语句.

Here the 'responseEntity' value will not be null and we can use it to perfectly assert a statement.

这篇关于我如何模拟 RestTemplate 交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆