3

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")    

}
Marco
  • 15,101
  • 33
  • 107
  • 174

3 Answers3

4

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 {
    ...
}
Community
  • 1
  • 1
6324
  • 4,678
  • 8
  • 34
  • 63
1

@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" />
Peter Niederwieser
  • 121,412
  • 21
  • 324
  • 259
  • Earlier on i tried to do more or less the same with a PropertyPlaceholderConfigurer, but i could not get this to work together with the @Value annotation. Your way of using the util:properties works perfect! – Marco Jul 04 '11 at 09:24
  • Is it also possible to use the PropertyPlaceholderConfigurer for this? – Marco Jul 04 '11 at 09:37
0

use jvm system properties "java -DdbUsername=bbbb"

Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327