JUnit:如何按Spring的意图访问Spring配置?

时间:2011-06-08 06:46:53

标签: spring junit

有一个tutorial video介绍了Spring MVC 3.0。在演示项目中,他们使用以下目录结构:

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

假设我有一个Maven支持的项目,我想使用Spring的配置编写JUnit测试。目前我们使用JUnit 4.8.2。这显然需要加载上面列出的三个文件。

在测试中,我可以使用注释,如

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

但是,找不到XML文件。我查看了类路径并注意到,默认情况下只包含<proj>/target/classes<proj>/target/test-classes

一个明显的解决方案是为类路径添加正确的路径,但我不知道这是不是春天的人想到的。

因此,我的问题是:我需要做什么来加载配置文件,同时让它看起来好像我是使用Spring的全程编码器?

2 个答案:

答案 0 :(得分:5)

另一种选择是使用文件系统资源加载器:

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

答案 1 :(得分:2)

你应该把&#34;正常&#34;资源文件夹中的spring配置,但不在webapp文件夹中:src\main\ressources\WEB-INF\spring\root/spring-context.xml。然后你可以在没有测试问题的情况下访问它。

仅将与Web相关的spring配置(servlet-context.xml)放在webapp文件夹中。


您描述的结构是由STS-Spring-Template生成的结构:MVC-Template,但Spring-ROO和Spring-Fuse生成我所描述的结构。 例如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>