Preface: My default mode of operation is using an IoC container and constructor injection. This makes testing with mocked dependencies trivial.
I am starting to develop an IntelliJ plugin and I want to make use of inversion of control. Since this is a plugin there isn't really an option of a container (right?) so I suppose I need to use a Service Locator pattern.
How do I test using mocks with the Service Locator pattern?
The best way that I can think of is to use an interface for my locator, set it in the default constructor of each service using a static getter, and have a setter so that I can set a mocked locator. It would look something like this:
public class MyService {
private IServiceLocator locator;
public MyService() {
setLocator(ServiceLocator.locator());
}
public void setLocator(IServiceLocator locator) {
this.locator = locator;
}
}
Now I can mock the IServiceLocator and set that on MyService in my test. I can then expect a call like locator.dependency1() and make it return a mocked dependency.
My main issue with this approach is the locator setter that is only there to support testing. Is there a better way?