How to inject property values into a Spock test?

2019-05-14 13:21发布

When using a Spock test, i have hardcoded some properties hardcoded into the spock test. The example is a JDBC url. I tried the @Value annotation together with a propertie file, but this seems not to work as my test has no stereotype. Are there any other solutions to inject property values?

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

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

}

3条回答
唯我独甜
2楼-- · 2019-05-14 13:31

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 {
    ...
}
查看更多
倾城 Initia
3楼-- · 2019-05-14 13:37

use jvm system properties "java -DdbUsername=bbbb"

查看更多
再贱就再见
4楼-- · 2019-05-14 13:39

@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" />
查看更多
登录 后发表回答