当使用Spock测试时,我已经硬编码了一些硬编码到spock测试中的属性。该示例是JDBC URL。我尝试了@Value注释和一个属性文件,但这似乎不起作用,因为我的测试没有刻板印象。是否还有其他解决方案来注入属性值?
@ContextConfiguration(locations = "classpath*:applicationContext-test.xml")
class RepositoryTest extends Specification {
@Shared sql = Sql.newInstance("jdbc:sqlserver:// - room - for - properties")
}
答案 0 :(得分:2)
要使用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 {
...
}
答案 1 :(得分:1)
@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" />
答案 2 :(得分:0)
使用jvm系统属性“java -DdbUsername = bbbb”