我有從斯波克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? –