I need to test some legacy code, which uses a singleton in a a method call. The purpose of the test is to ensure that the clas sunder test makes a call to singletons method.
I have a workaround for mocking a Singleton class using reflection. While setting up your tests, you might consider doing the following.
@Mock
private MySingletonClass mockSingleton;
private MySingletonClass originalSingleton;
@Before
public void setup() {
originalSingleton = MySingletonClass.getInstance();
when(mockSingleton.getSomething()).thenReturn("Something"); // Use the mock to return some mock value for testing
// Now set the instance with your mockSingleton using reflection
ReflectionHelpers.setStaticField(MySingletonClass.class, "instance", mockSingleton);
}
@After
public void tearDown() {
// Reset the singleton object when the test is complete using reflection again
ReflectionHelpers.setStaticField(MySingletonClass.class, "instance", null);
}
@Test
public void someTest() {
// verify something here inside your test function.
}
The ReflectionHelpers
is provided by Robolectric
in Android. However, you can always write your own functions which can help you with this. You can check the question here to get an idea.