使用弹簧配置文件时,将bean自动装配到TestNG测试的问题

时间:2014-08-04 08:37:26

标签: java spring testng spring-profiles

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

我有一个这样的测试类:

@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符合autowire candindate,找到0

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

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

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

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

2 个答案:

答案 0 :(得分:1)

为了获得更精确的答案,我建议您添加stacktrace和主要配置(您声明应该被测试bean替换的bean)。

以下是一般概念:

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

步骤:

  1. 您创建了main-config.xml 包含PropertyPlaceholderConfigurer并使用profile =“default”
  2. 标记它
  3. 使用PropertyPlaceholderConfigurer的测试实现创建test-config.xml (不要忘记使用profile =“MyTestProfile”标记test-config.xml或仅使用profile =“MyTestProfile”标记PropertyPlaceholderConfigurer
  4. 比将test-config.xml和main-config.xml导入测试
  5.  @ContextConfiguration(locations = { "classpath:META-INF/main-config.xml","classpath:META-INF/test-config.xml" })
     @ActiveProfiles("MyTestProfile")
     public class Test extends AbstractTestNGSpringContextTests {}
    

    它应该工作。祝你好运。

答案 1 :(得分:1)

尝试按照How to set JVM parameters for Junit Unit Tests?为实际运行测试的VM设置系统变量 - 它与运行maven的VM不同。

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

您可以使用maven系统参数来设置maven的调用(或使用maven配置文件)。