Search code examples
unit-testingjunitmockito

Mock objects which are created insinde another object


I'm trying to create a UnitTest for a class using JUnit and Mocktio. Inside this class, there are several calls to a method from a singleton, like

Singleton.getInstance().doSomething(value);

where I know the type of value. (There are no parameters in the constructor or any method for handling the singleton reference) Is it possible to mock the Singleton? My first idea was just to call Mockito.mock(Singleton.class) and pass it as a parameter, but then I would have to change this class to accept the singleton as a parameter - which does not make sense to me.

(I agree that this might be a design flaw, but at the moment I am not able to refactor the use of that singleton).


Solution

  • The issue here is that Mockito does not allow for mocking static methods (getInstance). However JMockit and Powermock both do allow for this.

    Another option might to use Mockito depends on the code in getInstance. If this is checking / returning a field, you might be able to assign that field to a mock instance using reflection.