【问题标题】:Run Spring MVC webapp with different configuration during integration tests在集成测试期间使用不同的配置运行 Spring MVC webapp
【发布时间】:2013-01-23 20:00:18
【问题描述】:

我在 Maven 构建的 integration-test 阶段使用 maven-jetty-plugin 运行我的 Spring MVC webapp,并在其上运行各种测试。此时,我希望能够切换出一些 Spring 配置,以便在集成测试期间可以指向不同的 bean 实现。这样我就可以更改要运行的数据库,而不是使用生产连接设置。

我应该考虑哪种方法?我应该尝试对 servlet-context.xml 文件使用资源过滤吗?我应该有两个不同的配置文件吗?如何让它与 Jetty 插件完美搭配?

编辑:我正在考虑使用 Spring 的基于 Java 的 @Configuration 注释而不是 XML servlet-context 文件,并根据环境变量或类似变量切换我构造的 bean 类型,但这也感觉不对。

【问题讨论】:

  • 你的春季版是 >= 3.1 吗?
  • @JintianDeng 是的,我正在运行 Spring 3.2.0.RELEASE。

标签: maven spring-mvc


【解决方案1】:

我会建议使用spring profile+maven过滤:

  1. 在 pom.xml 中定义一个可以通过命令行覆盖的属性:-Dspring.profile.active=development

         <properties>
                <spring.profile.active>test</spring.profile.active>
         </properties>
    
  2. 在 pom.xml 中添加资源过滤。确保您的 web.xml 在目录 src/main/resources 中。

     <resources>  
           <resource>  
             <directory>src/main/resources</directory>  
             <filtering>true</filtering>  
           </resource>  
     </resources> 
    
  3. 激活web.xml中具体的spring profile,过滤后会替换${spring.profile.active}。

    <context-param>  
        <param-name>spring.profiles.active</param-name>  
        <param-value>${spring.profile.active}</param-value>  
    </context-param> 
    
  4. 在 spring 配置文件中定义 bean

    <beans profile="production">  
         <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>  
    </beans>  
    

【讨论】:

  • 虽然我没有遵循这组确切的更改,但这个答案确实将我引向了优秀的 Maven 属性插件,它允许我将 spring.profiles.active 属性设置绑定到 pre-integration-test 阶段 --这足以注入不同的@Profile-annotated beans。
【解决方案2】:

以前,我总是创建一个包含 jetty-maven-plugin 配置和集成测试配置的配置文件。

但是当我了解 spring-test-mvc 时,我转而使用它,因为使用 jetty-maven-plugin 在集成测试中想要实现的一切都可以实现。另外,您可以模拟所需的服务(例如,在不同应用中进行身份验证)。

所以我建议切换到 spring-test-mvc。恕我直言,jetty-maven-plugin 风格非常痛苦。

【讨论】:

  • 这对于使用模拟 HTTP 请求和响应进行单元测试看起来很有用,但我真的希望能够在 Jetty 中运行我的 webapp 来执行端到端验收测试,例如使用 Selenium。
  • 可以使用@Jintian DENG + properties-maven-plugin 的建议。通过在预集成测试期间设置 spring.profiles.active 属性来激活弹簧配置文件
猜你喜欢
  • 2013-05-17
  • 2017-10-29
  • 1970-01-01
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
  • 2015-03-09
相关资源
最近更新 更多