Search code examples
javaspringspring-bootmockitospy

Original Method Called even after using Mockito.Spy


I tried all the advice given on many websites but nothing seems to be working in my case.

Test class

@Autowired
Service service;

@Test
public void Test() throws Exception {
    Service service1 = Mockito.spy(service);
    JSONObject obj = new JSONObject();
    Mockito.doReturn(obj).when(service1).getFunc(any(JSONObject.class));
    String str = service1.sendFunc(any(JSONObject.class));
    assertNotEquals(null, str);
}

Sevice Class

public class Service {
    public String sendFunc(JSONObject arg) {
        String str = getFunc(arg);
    }
    public String getFunc(JSONObject arg) {
        return "Pass";
    }
}

After debugging I realised that even after mocking it. The original method getFunc() is being called and nothing seems to be the problem. Please help figure it out?


Solution

  • It got solved. Apparently, I was sending any(JSONObject.class) while using service1.sendFunc(any(JSONObject.class)) but when I sent new JSONObject() it worked properly. Thanks for helping!