I’m using Tomcat 6.0.33 with Java 6. I have this servlet …
public class SaveXmlServlet extends HttpServlet {
private CacheService cacheService;
public void init(ServletConfig config) throws ServletException {
cacheService = CacheServiceLocator.cacheService();
} // init
How can I redesign my servlet to …
- Take advantage of dependency injection so that a mocking framework like mockito can inject its own “cacheService” implementation
- Guarantee that there is only one instance of cacheservice in my jvm. Right now the line “CacheServiceLocator.cacheService()” guarantees this.
? I’m not using (or allowed to use) frameworks like Spring or Guice. Grateful for any thoughts on refactoring this. Thanks, – Dave
There are a few options, although I recommend smacking someone for not “letting” you use a framework. Two quickies; I’m sure there are others. I’d go the smacking route first.
You can mock static classes using a combination of EasyMock/Mockito and, say, PowerMock. Technically you don’t need to change anything at all to get the in-test behavior you want.
A class name provided by a servlet init parameter or JNDI resource could be used to create an instance of the cache locator. Providing a setter for the same allows a unit/etc. test to set it on the class.