java - 带有配置文件的 Spring 集成测试

标签 java spring spring-mvc spring-test

在我们的 Spring Web 应用程序中,我们使用 Spring bean 配置文件来区分三个场景:开发、集成和生产。我们使用它们连接到不同的数据库或设置其他常量。

使用 Spring bean 配置文件非常适合更改 Web 应用程序环境。

我们遇到的问题是我们的集成测试代码需要针对环境进行更改。在这些情况下,集成测试会加载 Web 应用程序的应用程序上下文。这样我们就不必重新定义数据库连接、常量等(应用 DRY 原则)。

我们如下设置集成测试。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = ["classpath:applicationContext.xml"])
public class MyTestIT
{
   @Autowired
   @Qualifier("myRemoteURL")  // a value from the web-app's applicationContext.xml
   private String remoteURL;
   ...
 }

我可以使用 @ActiveProfiles 让它在本地运行,但这是硬编码的,会导致我们的测试在构建服务器上失败。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = ["classpath:applicationContext.xml"])
@ActiveProfiles("development")
public class MyTestIT
{ ... }

我也尝试使用 @WebAppConfiguration 希望它可能以某种方式从 Maven 导入 spring.profiles.active 属性,但这不起作用。

另外需要注意的是,我们还需要配置我们的代码,以便开发人员可以运行 Web 应用程序,然后使用 IntelliJ 的测试运行程序(或其他 IDE)运行测试。这对于调试集成测试要容易得多。

最佳答案

正如其他人已经指出的那样,您可以选择使用 Maven 来设置 spring.profiles.active 系统属性,确保 使用 @ActiveProfiles,但这对于在 IDE 中运行的测试并不方便。

对于设置 Activity 配置文件的编程方式,您有几个选择。

  1. Spring 3.1:编写自定义 ContextLoader,通过在上下文的 Environment 中设置 Activity 配置文件来准备上下文。
  2. Spring 3.2:自定义 ContextLoader 仍然是一个选项,但更好的选择是实现 ApplicationContextInitializer 并通过 initializers 属性对其进行配置@ContextConfiguration。您的自定义初始化程序可以通过以编程方式设置 Activity 配置文件来配置 Environment
  3. Spring 4.0:上述选项仍然存在;然而,从 Spring Framework 4.0 开始,有一个新的专用 ActiveProfilesResolver API 正是为此目的:以编程方式确定要在测试中使用的 Activity 配置文件集。 ActiveProfilesResolver 可以通过 @ActiveProfilesresolver 属性注册。

问候,

Sam(Spring TestContext 框架的作者)

关于java - 带有配置文件的 Spring 集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551681/

相关文章:

java - Spring MVC,在@service层处理错误并发送给jsp

java - 如何自动(输入时)扩展和收缩 EditTexts 的列以显示所有符号?

java - Collector 根据对象的一个​​属性创建一个List of List

java - "Write operations are not allowed in read-only mode"错误 : confused with Spring @Service @transaction @Repository and Hibernate

java - 在 Spring Data neo4j 中使用 RelationshipEntity 保存节点的正确方法是什么?

java - Websphere 8.5.5 上的 Spring Data JPA + Hibernate

java - 在Springboot应用程序中使用monad来捕获异常

spring - CSRF与Spring Security集成时, session 超时导致Spring MVC中的访问被拒绝

java - 如何以与驱动程序无关的方式与 DB(SQL Server、PG)建立 SSL 连接?

java - 如何在 Jersey 中获取上传文件的 MIME 类型