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.
As a beginner in Software Development, IMO, dependency injection of a singleton class in a driver/otherservice is a good option. As we can control creation of a single instance of the class and still be able to mock the static methods (as you might have guessed, I have util services in my mind) without using something like PowerMock to mock the static methods (IME which was little painful) I am very much open to listen about it from experienced folks from SOLID or Good OO design principle perspective.
public class DriverSnapshotHandler {
private FormatterService formatter;
public DriverSnapshotHandler() {
this(FormatterService.getInstance());
}
public DriverSnapshotHandler (FormatterService formatterService){
this.formatter = formatterService;
}
public String getImageURL() {
return FormatterService.getInstance().formatTachoIcon();
}
}
and then test using Mockito, something like this.
@Test
public void testGetUrl(){
FormatterService formatter = mock(FormatterService.class);
when(formatter.formatTachoIcon()).thenReturn("TestURL");
DriverSnapshotHandler handler = new DriverSnapshotHandler(formatter);
assertEquals(handler.getImageURL(), "TestUrl";
}