本文介绍了Mockito 不适用于 RestTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 mockito 来模拟 RestTemplate 交换调用.以下是我使用过的,但它没有选择模拟的 RestTemplate.

I am using mockito to mock a RestTemplate exchange call. Following is what I've used, but it's not picking up the mocked RestTemplate.

模拟通话.

ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, userId);

模拟的 RestTempate 如下.

The mocked RestTempate as follows.

Mockito.when(restTemplate.exchange(
            Matchers.anyString(),
            Matchers.any(HttpMethod.class),
            Matchers.<HttpEntity<?>> any(),
            Matchers.<Class<String>> any(),
            Matchers.anyString())).
            thenReturn(responseEntity);

知道这里出了什么问题吗?这与 @RunWith(PowerMockRunner.class) 一起运行,因为我在模拟静态内容.

Any idea what went wrong here? This runs with @RunWith(PowerMockRunner.class) Since I am mocking a static content.

推荐答案

signatureObject... 作为最后一个参数,所以你必须使用 anyVarArg().这在这里工作正常:

The signature has Object... as last param, so you have to use anyVarArg(). This is working fine here:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class Foo {
    @Mock
    private RestTemplate restTemplate;

    @Test
    public void testXXX() throws Exception {
        Mockito.when(this.restTemplate.exchange(Matchers.anyString(), Matchers.any(HttpMethod.class), Matchers.any(), Matchers.<Class<String>>any(), Matchers.<Object>anyVararg()))
               .thenReturn(ResponseEntity.ok("foo"));

        final Bar bar = new Bar(this.restTemplate);
        assertThat(bar.foobar()).isEqualTo("foo");
    }

    class Bar {
        private final RestTemplate restTemplate;

        Bar(final RestTemplate restTemplate) {
            this.restTemplate = restTemplate;
        }

        public String foobar() {
            final ResponseEntity<String> exchange = this.restTemplate.exchange("ffi", HttpMethod.GET, HttpEntity.EMPTY, String.class, 1, 2, 3);
            return exchange.getBody();
        }
    }
}

注意:使用anyVarArg,一个cast (Object) Matches.anyVarArgs() 也可以避免模棱两可的方法错误.

Note: the use of anyVarArg, a cast (Object) Matches.anyVarArgs() is also possible to avoid the ambiguous method error.

这篇关于Mockito 不适用于 RestTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:03
查看更多