'Mocking RestTemplate postforEntity

I have a service class which looks like -

class A {
   @Autowired
   RestTemplate restTemplate;
   public void method() {
       res = restTemplate.postForEntity("http://abc", entity, Employee.class);
       resBody = res.getBody();      
   }
}

Following is the Test Class for it-

class TestA {
   @Mock
   RestTemplate restTemplate;
   @InjectMocks
   A obj;
   void testMethod1() {
       res = ....
       when(restTemplate.postForEntity(any(), any(), any()).thenReturn(res);
   }
   void testMethod2() {
       res = ....
       when(restTemplate.postForEntity(anyString(), any(), any()).thenReturn(res);
   }
}

testMethod1 fails throwing NullPointerException on "res.getBody() from A.method()" while testMethod2 runs successfully

Why is any() not working here while anyString() works? I thought any() works for any data type.



Solution 1:[1]

My problem was similar, casting null to String worked for me: when(restTemplateMock.postForEntity((String)isNull(), any(), eq(List.class))) .thenReturn(responseEntityMock);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TimP