spring - 如何将属性值注入(inject)到 Spock 测试中?

标签 spring groovy dependency-injection spock

使用 Spock 测试时,我将一些属性硬编码到 spock 测试中。该示例是 JDBC url。我尝试将 @Value 注释与属性文件一起使用,但这似乎不起作用,因为我的测试没有构造型。还有其他解决方案来注入(inject)属性值吗?

@ContextConfiguration(locations = "classpath*:applicationContext-test.xml")
class RepositoryTest extends Specification {

    @Shared sql = Sql.newInstance("jdbc:sqlserver:// - room - for - properties")    

}

最佳答案

要使用PropertySourcesPlaceholderConfigurer,请添加@Configuration类:

@Configuration
@PropertySource("classpath:database.properties")
public class DatabaseConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

引用号是here .

然后,在 Spock 中:

@Value('${foo.bar}') //Use single quote.
String fooBar

使用单引号的原因是here .

您可能需要将 @ContextConfiguration 添加到您的 Spock 类中:

@ContextConfiguration(classes = DatabaseConfig .class)
class Test extends Specification {
    ...
}

关于spring - 如何将属性值注入(inject)到 Spock 测试中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6536289/

相关文章:

java.lang.NoClassDefFoundError : org/springframework/context/support/ClassPathXmlApplicationContext 错误

groovy - 我可以在 Groovy 中覆盖 cast 运算符吗?

java - Guice 提供者方法是否尊重范围?

Spring - 不是托管类型 : class

java - 如何获取 Feign 客户端的名称?

Groovy,如何传入内联变量,即文件中的 ${variable} 语句?

java - 为什么 Dagger 2 中需要@SubComponent?

c# - 使用具有依赖注入(inject)的策略和工厂模式

java - Spring 4 + Jersey 集成@Autowired

unit-testing - Spock 数据驱动测试,使用类来测试 "instanceof"断言