0

我目前正在完善我们拥有的测试框架。对于当前的需求,我们必须支持多个弹簧配置文件,并多次运行我们的测试,每次使用不同的配置文件。每个配置文件都针对不同的测试环境,因此可以执行具有不同逻辑的不同测试集。

我有一个这样的测试课:

@ContextConfiguration(locations = { "classpath:META-INF/test-context.xml" })
public class Test extends AbstractTestNGSpringContextTests {
    @Autowired
    ProfileSpeciticBean profileSpecificBean;

    ...
}

这里,ProfileSpecificBean是一个接口,由不同的类实现。要注入的实际实现由活动的 Spring 配置文件决定,我使用的是 Spring XML 上下文。我正在使用-Dspring.profiles.active=profileName命令使用 Maven 构建项目,因此期望测试能够捕获通过的配置文件。

但是,当前测试在完整堆栈跟踪中失败并出现此错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException:没有找到依赖项的 ProfileSpeciticBean 类型的合格 bean:预计至少有 1 个符合自动装配候选资格的 bean,找到 0

在对这个主题进行了一些研究之后,我发现AbstractTestNGSpringContextTests期望@ActiveProfiles在测试类之上有一个注释。所以,这段代码有效:

 @ContextConfiguration(locations = { "classpath:META-INF/test-context.xml" })
 @ActiveProfiles("profile1")
 public class Test extends AbstractTestNGSpringContextTests ...

这样做的问题是:我想避免在我的类中硬编码配置文件名称。我需要为不同的配置文件运行相同的测试类,只需更改命令行脚本。

以上可能吗?有没有办法让 TestNG 知道命令行配置文件,并重新使用相同的测试?我需要避免重复代码和配置以使我的测试运行,因此为每个配置文件创建两个测试类不是我想要的。

4

2 回答 2

1

为了获得更准确的答案,我建议您添加堆栈跟踪和您的主要配置部分(您声明的 bean 应该被测试 bean 替换)。

这是一般的想法:

假设您想根据您的个人资料更改 PropertyPlaceholderConfigurer。

脚步:

  1. 您创建包含 PropertyPlaceholderConfigurer 的 main-config.xml 并用 profile="default" 标记它
  2. 您使用 PropertyPlaceholderConfigurer 的测试实现创建 test-config.xml
    (不要忘记使用 profile="MyTestProfile" 标记 test-config.xml 或仅使用 profile="MyTestProfile 标记 PropertyPlaceholderConfigurer)
  3. 比你将 test-config.xml 和 main-config.xml 都导入你的测试

 

 @ContextConfiguration(locations = { "classpath:META-INF/main-config.xml","classpath:META-INF/test-config.xml" })
 @ActiveProfiles("MyTestProfile")
 public class Test extends AbstractTestNGSpringContextTests {}

它应该工作。祝你好运。

于 2014-08-04T09:07:31.293 回答
1

尝试遵循如何为 Junit 单元测试设置 JVM 参数?为实际运行测试的虚拟机设置系统变量 - 它与运行 maven 的虚拟机不同。

在那里设置您的个人资料。

您可以使用 maven 系统参数通过调用 maven(或使用 maven 配置文件)进行设置。

于 2014-08-04T10:25:41.323 回答