Problem
I am working on a RESTful API using Jersey. To allow mocking of objects in my unit tests, I use the dependency injection framework Guice (in particular Guice-Servlet). It is possible to filter requests through your own Filter implementations, by overriding the configureServlet() method of your ServletModule and adding:
bind(MyFilter.class).in(Singleton.class);
filter("path").through(MyFilter.class);
When running my webapp in Tomcat, my requests are correctly filtered through this MyFilter class. But, in my JUnit tests none of my requests are filtered through it. Can anybody help me find the problem?
Example
Bitbucket repository with my example code
- web / WEB-INF / web.xml : used by Tomcat. Defines ApplicationSetup as the GuiceFilter on path '/api/*'.
- src / main / java / ApplicationSetup.java : creates the Guice Injector for the production environment (Tomcat webserver). Uses ApplicationModule as one of its ServletModules.
- src / main / java / ApplicationModule.java : ServletModule that configures and binds MyFilter and the Jersey endpoints on path '/api/*'.
- src / main / java / endpoints / HelloWorldEndPoint.java : Simple endpoint at path '/api/helloworld' with method for GET request.
- src / main / java / MyFilter.java : Sets the 'Via' header on the response if the request passed through this filter.
- src / test / java / TestApplicationSetup.java : creates the Guice Injector for the test environment (Grizzly webserver). Like ApplicationSetup this also uses ApplicationModule as one of its ServletModules. In addition, it has a method to start the Grizzly webserver for test purposes.
- src / test / java / TestHelloWorldEndPoint.java : Performs a GET request on /api/helloworld and checks if the response has the 'Via' header set to MyFilter. This fails.
The main point here is the ApplicationModule, which is used by both environments to bind the filter. If you check the logging of the example you'll notice that MyFilter is initialised in both environments (simple print in the init() method). You'll also notice that the ApplicationModule is used for the servlet configuration in both environments. But somehow the Grizzly webserver ignores the Filter.
I've been struggling with this problem for quite some time now, and thus have now taken the time to ask this question here. I really hope somebody can help me with this. Workarounds are also appreciated.