[英]How to return list for mock in groovy spock test
我從Spock 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:預期的:[com.example.SomeObject @ 1fa268de,com.example.SomeOjbect @ 4f6ee6e4]實際的:null
因此,這意味着從repository.all
方法返回null
而不是我的預期列表,這使我感到困惑。 問題是:使用spock和groovy測試時,如何從模擬實例中實際返回列表?
您可以嘗試將存根零件移至交互檢查階段,例如
def 'should collect items from repository'() {
given:
List<SomeObject> expected = [new SomeObject(), new SomeObject()]
when:
List<SomeObject> actual = processor.all
then:
1 * repository.all >> expected
and:
expected == actual
}
另外,您不必使用JUnit的assertEquals
-Groovy允許您使用==
運算符比較兩個對象。
我已經在基於Spock的簡單應用程序中檢查了您的示例,效果很好。 我使用Spock 0.7-groovy-2.0
1.0-groovy-2.4
和1.2-groovy-2.4-SNAPSHOT
,並與所有Spock版本一起使用。 無論如何,我過去也遇到過一些類似的問題,因為在這些情況下,交互檢查確實可以解決問題。 希望能幫助到你。
根據白盒測試,更好地測試所實施的完全相同。 processor.all
將按原樣返回repository.all
的結果。 因此,最好測試一下這個事實。
根據Szymon Stepniak提供的正確代碼,可以將測試簡化為:
def 'should collect items from repository'() {
given:
def expected = []
when:
def actual = processor.all
then:
1 * repository.all >> expected
and: 'make sure we got the same expected list instance'
actual.is(expected)
}
在.is()
我們驗證相同的引用。
結果,它不符合列表的內容,可以為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.