How to inject property values into a Spock test?

南笙酒味 提交于 2019-12-06 03:26:00

@Shared properties cannot be injected, but something like this should work (with Spring 3):

@Value("#{databaseProperties.jdbcUrl}")
String jdbcUrl

Sql sql

def setup() {
  if (!sql) {
    sql = new Sql(jdbcUrl)
  }
}

This assumes that you have defined "databaseProperties" in your bean definition file:

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

To use PropertySourcesPlaceholderConfigurer, add a @Configuration class:

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

Reference is here.

And then, in Spock:

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

The reason to use single quote is here.

And you probably need to add @ContextConfiguration to your Spock class:

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

use jvm system properties "java -DdbUsername=bbbb"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!