开发者

JUnit: how to access Spring configuration as Spring has intended?

There is a tutorial video that introduces Spring MVC 3.0. In the demo-project they use the following directory structure:

<proj>
   src
      main
         webapp
            WEB-INF
               spring
                  appServlet
                     controllers.xml
                     servlet-context.xml
                  root-context.xml

Let's say I have a project with Maven-support and I want to write JUnit tests using Spring's configuration. Currently we use JUnit 4.8.2. This would obviously require to load the three files listed above.

In the test I could use annotations like

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:/WEB-INF/spring/**/*.xml")

Howev开发者_如何学编程er, that doesn't find the XML-files. I took a look at the classpath and noticed, that only the <proj>/target/classes and <proj>/target/test-classes are included by default.

One obvious solution would be to add the proper path to the classpath, but I don't know if that is what the guys at Spring had in mind.

Therefore, my question: What do I need to do to load the configuration files while letting it look as if I'm the total pro-coder using Spring?


Another option is to use file system resource loader:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")


You should put the "normal" spring configuration in the resources folder but not in the webapp folder: src\main\ressources\WEB-INF\spring\root/spring-context.xml. Then you can access it without problems from the test.

Put only the web related spring configuration (servlet-context.xml) in the webapp folder.


The structure that you described is the one generated by the STS-Spring-Template:MVC-Template, however Spring-ROO and Spring-Fuse generate the structure that I have described. For example Spring ROO:

<project>/src/main/resources/META-INF/spring/applicationContext.xml
<project>/src/main/webapp/WEB-INF/spring/webmvc-config.xml
<project>/src/main/webapp/WEB-INF/web.xml

web.xml:

...
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
</context-param>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜