自 Spock 1.1 以来,可以在规范类之外创建模拟DetachedMockFactory
和SpockMockFactoryBean
。spock
还支持基于 XML 的配置的命名空间。您可以在文档中找到使用示例。
使用基于 Java 的配置的 Spring 测试,DetachedMockFactory
如下所示:
@ContextConfiguration(classes = [TestConfig, DiceConfig])
class DiceSpec extends Specification {
@Autowired
private RandomNumberGenerator randomNumberGenerator
@Subject
@Autowired
private Dice dice
def "uses the random number generator to generate results"() {
when:
dice.roll()
then:
1 * randomNumberGenerator.randomInt(6)
}
static class TestConfig {
private final mockFactory = new DetachedMockFactory()
@Bean
RandomNumberGenerator randomNumberGenerator() {
mockFactory.Mock(RandomNumberGenerator)
}
}
}
@Configuration
class DiceConfig {
@Bean
Dice dice(RandomNumberGenerator randomNumberGenerator) {
new Dice(randomNumberGenerator)
}
}
基于 XML 的配置看起来像这样:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spock="http://www.spockframework.org/spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.spockframework.org/spring http://www.spockframework.org/spring/spock.xsd">
<spock:mock id="randomNumberGenerator" class="RandomNumberGenerator"/>
</beans>
确保包含spock-spring
依赖项:
testCompile group: 'org.spockframework', name: 'spock-spring', version: '1.1-groovy-2.4-rc-3'