Given a unit test class that needs to use a specific service, it seems that there are different ways to fake the behaviour of the service, such as using a mocking framework, or implement a stub class.
For instance, a service to read/write to disk:
public interface FileServiceInterface {
public void write(String text);
public String read(String fileName);
}
I might have a class that fakes its behaviour and later use it in the test class, injecting the Stub instead of the real implementation:
public class FileServiceStub implements FileServiceInterface {
ConcurrentHashMap<String, String> content = new ConcurrentHashMap<>();
public void write(String fileName, String text) {
content.put(fileName, text);
}
public String read(String fileName) {
return content.get(fileName);
}
}
Other option is to let Mockito (for example) intercept the calls to the service directly in the test class:
public class TestExample {
@Mock
private FileServiceImpl service; // A real implementation of the service
@Test
void doSomeReadTesting() {
when(service.read(any(String.class))).thenReturn("something");
...
}
}
I would like to know which of these alternatives is the best (or currently most accepted) approach, and if there's any other/better option. Thanks.