How to mock the RestTemplate getForObject

49 Views Asked by At

I am not able to mock below piece of restTemplate getForObject , Its giving assertion errors when i run my test case , can some one help me how to mock?.

ServiceClient.class

String localizationDetails = getRestTemplate(RestClientEnum.LOCALIZATION_ZIP.getValue())
                    .getForObject(localizationUrl, String.class);

Test class

@Test
    public void validateZipCodeTest() throws Exception {
        String zipCode = "98011";
        when(restTemplate.getForObject(ArgumentMatchers.any(),
                String.class)).thenReturn(xmlString);
        zipCodeDetails = serviceClient.validateZipCode(zipCode);
        assertNotNull(zipCodeDetails);
}

Error

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 2 matchers expected, 1 recorded:

This exception may occur if matchers are combined with raw values: //incorrect: someMethod(any(), "raw String"); When using matchers, all arguments have to be provided by matchers. For example: //correct: someMethod(any(), eq("String by matcher"));

For more info see javadoc for Matchers class.

1

There are 1 best solutions below

0
On

The error tells you the problem exactly:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 2 matchers expected, 1 recorded:

when(restTemplate.getForObject(
    ArgumentMatchers.any(),            // a matcher
    String.class                       // NOT a matcher
)).thenReturn(xmlString);

You can use matchers for none of the arguments (all values must exactly) or use matchers for all of the arguments. You cannot use matchers only for some.

The docs are quite explicit about it and showcase your example almost exactly:

Warning on argument matchers:

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

The following example shows verification but the same applies to stubbing:

verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));
//above is correct - eq() is also an argument matcher

verify(mock).someMethod(anyInt(), anyString(), "third argument");
//above is incorrect - exception will be thrown because third argument is given without an argument matcher.

How to fix? Use matchers for all arguments:

when(restTemplate.getForObject(
    ArgumentMatchers.any(),            // a matcher
    ArgumentMatchers.eq(String.class)  // also a matcher now
)).thenReturn(xmlString);