Question

How to mock getForObject method in RestTemplate class using jmockit -

I am trying to do like this -

   @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)}";
        }
    };  
}

But every time I am getting this error-

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

Any thoughts what wrong I am doing here?

UPDATE:-

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)
Était-ce utile?

La solution

In fact, the signature of the @Mock method does not match the signature of the mocked method, as the exception message says.

To see why, notice there is only one real implementation of the RestTemplate#getForObject(String, Class, Object[]) method. Then, consider what would happen for the following call:

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

Naturally, this call should not redirect to a @Mock method having a return type of String. So, the correct mock method should be:

new MockUp<RestTemplate>() {
    @Mock
    <T> T getForObject(String url, Class<T> responseType, Object... urlVariables) {
        return (T) "{(\"error\": \"missing data id\", \"data_id\":2001)}";
    }
};
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top