如何使用jmockit模拟RestTemplate getForObject方法?

时间:2014-03-15 17:39:49

标签: java unit-testing mocking resttemplate jmockit

如何使用getForObjectRestTemplate课程中模拟jmockit方法 -

我想这样做 -

   @Test
    public void test2DataClient() {

    new MockUp<RestTemplate>() {

        @Mock
        public String getForObject(String url, Class<String> responseType, Object... urlVariables) {
        return "{(\"error\": \"missing data id\", \"data_id\":2001)}";
        }
    };  
}

但每次我收到此错误 -

java.lang.IllegalArgumentException: Matching real methods not found for the following mocks:

有什么想法,我在这里做错了什么?

更新: -

Full StackTrace -

java.lang.IllegalArgumentException: Matching real methods not found for the following mocks:
com.host.dataclient.test.DataTest$3#getForObject(String url, Class responseType, Object[] urlVariables)
    at com.host.dataclient.test.DataTest$3.<init>(DataTest.java:649)
    at com.host.dataclient.test.DataTest.test25dataclient(DataTest.java:649)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:602)
    at java.lang.reflect.Method.invoke(Method.java:602)
    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:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

1 个答案:

答案 0 :(得分:1)

事实上,@Mock方法的签名与模拟方法的签名不匹配,正如异常消息所示。

要了解原因,请注意RestTemplate#getForObject(String, Class, Object[])方法只有一个真正的实现。然后,考虑以下调用会发生什么:

Integer i = restTemplate.getForObject("...", Integer.class);

当然,此调用不应重定向到返回类型为@Mock的{​​{1}}方法。 所以,正确的模拟方法应该是:

String