在我们的 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 配置文件的编程方式,您有几个选择。
- Spring 3.1:编写自定义
ContextLoader
,通过在上下文的Environment
中设置 Activity 配置文件来准备上下文。 - Spring 3.2:自定义
ContextLoader
仍然是一个选项,但更好的选择是实现ApplicationContextInitializer
并通过initializers
属性对其进行配置@ContextConfiguration
。您的自定义初始化程序可以通过以编程方式设置 Activity 配置文件来配置Environment
。 - Spring 4.0:上述选项仍然存在;然而,从 Spring Framework 4.0 开始,有一个新的专用
ActiveProfilesResolver
API 正是为此目的:以编程方式确定要在测试中使用的 Activity 配置文件集。ActiveProfilesResolver
可以通过@ActiveProfiles
的resolver
属性注册。
问候,
Sam(Spring TestContext 框架的作者)
关于java - 带有配置文件的 Spring 集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551681/