2017-10-19 114 views
2

我有從斯波克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進行測試時從模擬實例返回列表?

+0

'repository.all >> expected'看起來像去除我。嘗試用'repository.all = new ArrayList(預期)'替換它' – injecteer

+0

我測試了你的代碼1:1,我改變的唯一的東西是'Object'而不是'SomeObject',它工作得很好,就像你期望的那樣工作。我嘗試了Spock 1.0-groovy-2.4和1.1-groovy-2.4,兩者都工作得很好。 – Vampire

+0

順便說一句,這是不適合你的或者短暫的PoC,試圖反映你的問題的確切代碼?也許你面臨類似的問題 - https://github.com/kiview/spring-spock-mock-beans-demo/issues/1? –

回答

3

您可以嘗試將存根部分移動到交互檢查階段,例如,

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.01.0-groovy-2.41.2-groovy-2.4-SNAPSHOT對它進行了測試,與所有Spock版本一起工作。無論如何,我在過去遇到過類似的問題,因爲交互檢查在這些情況下做了詭計。希望能幫助到你。

+0

感謝您提供有關交互檢查的提示 –

0

根據白盒測試更好地測試完全相同的實施。 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()我們驗證了相同的標號。

因爲它不是什麼列表,它可以只是空的。