【问题标题】:How to inject property values into a Spock test?如何将属性值注入 Spock 测试?
【发布时间】:2011-09-26 01:11:22
【问题描述】:

在使用 Spock 测试时,我已将一些属性硬编码到 spock 测试中。该示例是一个 JDBC url。我尝试了 @Value 注释和属性文件,但这似乎不起作用,因为我的测试没有刻板印象。还有其他注入属性值的解决方案吗?

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

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

}

【问题讨论】:

    标签: spring groovy dependency-injection spock


    【解决方案1】:

    要使用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 {
        ...
    }
    

    【讨论】:

    • 这个更有帮助
    【解决方案2】:

    @Shared 属性不能被注入,但是这样的东西应该可以工作(使用 Spring 3):

    @Value("#{databaseProperties.jdbcUrl}")
    String jdbcUrl
    
    Sql sql
    
    def setup() {
      if (!sql) {
        sql = new Sql(jdbcUrl)
      }
    }
    

    这假设你已经在你的 bean 定义文件中定义了“databaseProperties”:

    <util:properties id="databaseProperties" location="classpath:database.properties" />
    

    【讨论】:

    • 早些时候,我尝试使用 PropertyPlaceholderConfigurer 或多或少地做同样的事情,但我无法让它与 @Value 注释一起使用。您使用 util:properties 的方式非常完美!
    • 是否也可以为此使用 PropertyPlaceholderConfigurer?
    【解决方案3】:

    使用 jvm 系统属性“java -DdbUsername=bbbb”

    【讨论】:

      猜你喜欢
      • 2012-04-06
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 2016-09-25
      • 1970-01-01
      • 2017-03-18
      • 2019-04-30
      相关资源
      最近更新 更多