I have a web application, that contains a configuration xml file for one of my application services that is exposed as spring bean.
Also I have a standalone java application(which references my web app project from its pom.xml) in the same workspace, that runs tests using Spring TestContext framework and one of the tests checks the configuration of that XML file.
However I have a problem with accessing this xml file from the standalone app:
Before setting-up the test, in my previous configuration, the file was accessed through ServletContext and was located in WEB-INF/ folder. However, to make it accessable from the test project I had to move it to source/ folder and load it with getClassLoader().getResourceAsStream() method instead that of ServletContext. But it makes editing the file cumbersome because every time the app has to be redeployed.
Is it possible to keep the file in WEB-INF/ folder but load it from the referencing project during the test-runs?
P.S. Currently it’s an STS project with Tomcat server.
I ended up using Spring MockServletContext class and injecting it directly to my service bean, before the test runs, as my service implemented
ServletContextAware:If I had several classes using Servlet Context, then the better solution would be to use WebApplicationContext instead the default one (currently provided by DelegatingSmartContextLoader), but it would require implementing custom ContextLoader class and passing its class name to @ContextConfiguration annotation.
alternative and somewhat cleaner solution which later came to my mind is to refactor the service and inject
ServletContextvia@Autowiredinstead of messing withServletContextAware, and provide the bean of corresponding type(effectively aMockServletContextinstance).Possibly, in future the direct support ofMockServletContextfrom test classes will be added to Spring see SPR-5399 and SPR-5243.UPDATE FOR SPRING 3.2
In Spring 3.2 initialization of the servlet context became as simple as adding one
@WebAppConfigurationannotation:see details in the article