Reputation: 3016
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).
Upvotes: 0
Views: 49
Reputation: 69
Mocking static getInstance()
method is nowadays possible. You can simply do it like this:
class Test{
@Mock
protected MockedStatic<Singleton> singletonMock;
// Mocked Singleton instance, which is being returned from mocked static getInstance call
@Mock
protected Singleton mockedSingletonInstance;
private AutoCloseable closeable;
@BeforeEach
public void openMocks() {
// Search for @Mock annotated fields and initialize them.
// You can also always not to have @Mock annotation on field and do it by hand, like Mockito.mockStatic(Singleton.class)
closeable = MockitoAnnotations.openMocks(this);
this.singletonMock
.when(() -> Singleton.getInstance())
.thenReturn(mockedSingletonInstance);
}
@AfterEach
public void releaseMocks() throws Exception {
closeable.close();
}
Have a look at https://www.baeldung.com/mockito-mock-static-methods for more examples.
Upvotes: 1
Reputation: 32949
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.
Upvotes: 1