我有从斯波克Groovy中嘲笑接口返回所需的对象列表的问题:如何在常规斯波克测试模拟返回列表
public interface SomeRepository {
List<SomeObject> getAll();
}
所以我想嘲弄,在类:
@CompileStatic
class SomeProcessor {
private final SomeRepository repository
SomeProcessor(SomeRepository repository) {
this.repository = repository
}
List<SomeObject> getAll() {
return repository.all
}
}
而且我有一个测试:
class SomeProcessorSpec extends Specification {
private final SomeRepository repository = Mock(SomeRepository)
@Subject private final SomeProcessor processor = new SomeProcessor(repository)
def 'should collect items from repository'() {
given:
List<SomeObject> expected = [new SomeObject(), new SomeObject()]
repository.all >> expected
when:
List<SomeObject> actual = processor.all
then:
assertEquals(expected, actual)
}
}
当我尝试运行测试,我得到一个断言错误:
junit.framework.AssertionFailedError: Expected :[[email protected], [email protected]] Actual :null
因此,这意味着从repository.all
方法,它返回null
,而不是我的期望列表,这是混淆了我。问题是:如何在使用spock和groovy进行测试时从模拟实例返回列表?
'repository.all >> expected'看起来像去除我。尝试用'repository.all = new ArrayList(预期)'替换它' – injecteer
我测试了你的代码1:1,我改变的唯一的东西是'Object'而不是'SomeObject',它工作得很好,就像你期望的那样工作。我尝试了Spock 1.0-groovy-2.4和1.1-groovy-2.4,两者都工作得很好。 – Vampire
顺便说一句,这是不适合你的或者短暂的PoC,试图反映你的问题的确切代码?也许你面临类似的问题 - https://github.com/kiview/spring-spock-mock-beans-demo/issues/1? –