带型材的弹簧集成测试

2022-09-02 00:13:39

在我们的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
{ ... }

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

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


答案 1

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

对于设置活动配置文件的编程方法,您有几个选项。

  1. Spring 3.1:编写一个自定义,通过在上下文中设置活动配置文件来准备上下文。ContextLoaderEnvironment
  2. Spring 3.2:自定义仍然是一个选项,但更好的选择是实现 a 并通过 的属性进行配置。您的自定义初始值设定项可以通过以编程方式设置活动配置文件来配置 。ContextLoaderApplicationContextInitializerinitializers@ContextConfigurationEnvironment
  3. Spring 4.0:上述选项仍然存在;但是,从Spring Framework 4.0开始,有一个新的专用API专门用于此目的:以编程方式确定要在测试中使用的活动配置文件集。可以通过 的属性注册 。ActiveProfilesResolverActiveProfilesResolverresolver@ActiveProfiles

问候

Sam(Spring TestContext Framework的作者)


答案 2

我遇到了类似的问题:我想使用默认配置文件运行所有集成测试,但允许用户使用表示不同环境甚至数据库风格的配置文件进行覆盖,而无需更改@ActiveProfiles值。如果您将Spring 4.1 +与自定义ActiveProfilesResolver一起使用,这是可行的。

此示例解析程序查找系统属性 spring.profiles.active,如果它不存在,它将委托给默认解析程序,该解析程序仅使用@ActiveProfiles注释。

public class SystemPropertyActiveProfileResolver implements ActiveProfilesResolver {

private final DefaultActiveProfilesResolver defaultActiveProfilesResolver = new DefaultActiveProfilesResolver();

@Override
public String[] resolve(Class<?> testClass) {

    if(System.getProperties().containsKey("spring.profiles.active")) {

        final String profiles = System.getProperty("spring.profiles.active");
        return profiles.split("\\s*,\\s*");

    } else {

        return defaultActiveProfilesResolver.resolve(testClass);
    }
}

}

在你的测试类中,你可以像这样使用它:

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles( profiles={"h2","xyz"},
resolver=SystemPropertyActiveProfileResolver.class)
public class MyTest { }

当然,除了检查系统属性是否存在之外,您还可以使用其他方法来设置活动配置文件。希望这对某人有所帮助。


推荐