java 如何使用 mockito 模拟 Rest 模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30526247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:16:19  来源:igfitidea点击:

How to Mock Rest template using mockito

javajunitmockitoresttemplate

提问by Rithik_Star

I am writing junit for one class(Test) which has rest template call.

我正在为一个具有休息模板调用的类(测试)编写 junit。

response = restTemplate.exchange(uri, HttpMethod.POST,
                headersString, SomeObject.class)

I am writting junit using Mockito. The below mock statement throws error

我正在使用 Mockito 编写 junit。下面的模拟语句抛出错误

when(restTemplate.exchange(any(URI.class), any(HttpMethod.class),
                headersString , SomeObject.class)).

Help me how to put the rest template call in the when statement for junit using Mockito.

帮助我如何使用 Mockito 将其余模板调用放在 junit 的 when 语句中。

Error:

错误:

java.lang.IllegalArgumentException: 'url' must not be null
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:534)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:518)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:463)
    at (Test.java:80)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access
when(restTemplate.exchange(any(URI.class), any(HttpMethod.class),
     headersString , SomeObject.class)).
//   ^^              ^^
0(ParentRunner.java:42) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:184) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Misplaced argument matcher detected here: -> at (Test.java:81) You cannot use argument matchers outside of verification or stubbing. Examples of correct usage of argument matchers: when(mock.get(anyInt())).thenReturn(null); doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject()); verify(mock).someMethod(contains("foo")) Also, this error might show up because you use argument matchers with methods that cannot be mocked. Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode(). at org.mockito.internal.runners.util.FrameworkUsageValidator.testFinished(FrameworkUsageValidator.java:25) at org.junit.runner.notification.RunNotifier.notifyListener(RunNotifier.java:145) at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:41) at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:142) at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:37) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:82) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner.run(ParentRunner.java:193) at org.junit.runners.ParentRunner.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access
when(restTemplate.exchange(any(URI.class), any(HttpMethod.class), 
     eq(headersString), eq(SomeObject.class))).
0(ParentRunner.java:42) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:184) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

回答by

As probably stated by the error message, you can notmix matchers and fixed values (no matcher), like this:

正如错误消息可能说,你不能混用匹配器和固定值(不匹配),就像这样:

ResponseEntity<String> responseEntity = new ResponseEntity<String>("sampleBodyString", HttpStatus.ACCEPTED);
when(restTemplate.exchange(
 Matchers.anyString(),
 Matchers.any(HttpMethod.class),
 Matchers.<HttpEntity<?>> any(), 
 Matchers.<Class<String>> any())).thenReturn(responseEntity);

You have to use the eq()matchers for fixed values, like this:

您必须将eq()匹配器用于固定值,如下所示:

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


From the Matchersjavadoc:

Matchersjavadoc

Warning:

If you are using argument matchers, all arguments have to be provided by matchers.

警告:

如果您使用参数匹配器,则所有参数都必须由匹配器提供。

回答by Shyam Elakapalli

Below code works,

下面的代码有效,

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

回答by Dheeraj

A more reliable solution could be as below mentioned. I have mentioned the import statements too which have worked for me. The below piece of code perfectly mocks the rest template.

更可靠的解决方案可能如下所述。我也提到了对我有用的导入语句。下面的代码完美地模拟了其余模板。

##代码##

This is the actual template to mock.

这是要模拟的实际模板。

##代码##

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

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