javaunit-testingmockitospy

Spy actual method call, not able to stub the calls in the actual method by mocking


I've got an existing class for which I need to write unit test cases using Junit and Mockito. The method I'm trying to test calls a method of another class which returns nothing but populates a Map which is passed as a parameter to the method call. I'm using @Spy to call the actual method as I want to get the Map in my test method for further usage. But the actual method that is being called has dependency on another Utility class whose behavior I'm trying to mock using @Mock but the Utility class is not being mocked and I'm getting an NPE. Can someone please help with what needs to be done in this case.

public class MyClass {
  
  public Response method() {//Method to be tested
    Map<String, Object> mapToBePopulated = new HashMap<>();
    supportClass.populateMap(mapToBePopulated);
  }
}
public class SupportClass {
  @Autowired
  UtilityClass utility;

  public void populateMap(Map<String, List<Object>> mapToBePopulated) {
    //populateMap
    utility.doSomething(mapToBePopulated); //I'm mocking Utility class but when the debugger comes to this line the utility object is Null which throws the NPE.
  }
  //this method is being stubbed
  public Object doSomething(String one) {
  //some lines
  }
}

Edit: Added other methods that are part of the SupportClass which I'm stubbing so can't really use @InjectMocks here. Is there a way to avoid calling the actual method and still populate the Map?


Solution

  • create a fake support class that extends the real one for the test purpose. Override the populateMap method with a predictible logic that suits your test case. In your test, pass the fake support class instead of the real one