2014-01-05 21 views
2

鑑於以下接口:斯波克:有什麼不對的嘲諷

interface Bundle { 
    String getName() 

    String getVersion() 
} 

和下面的方法:

String log(Bundle b) { 
    return "${b.getName()}: ${b.getVersion()}" 
} 

這斯波克測試失敗:

def "my test"() { 
     given: 
     def bundle = Mock(Bundle) 
     bundle.getName() >> "name" 
     bundle.getVersion() >> "1.0.0" 

     when: 
     def x = log(bundle) 

     then: 
     x == "name: 1.0.0" 
     1 * bundle.getName() 
     1 * bundle.getVersion() 

    } 

這裏是錯誤:

condition not satisfied: 
x == "name: 1.0.0" 
| | 
| false 
| 8 differences (27% similarity) 
| n(ull): (null-) 
| n(ame): (1.0.0) 
null: null 

如果我刪除兩個驗證(1 * bundle.getName()1 * bundle.getVersion()),則測試將爲綠色。

任何想法我的代碼有什麼問題?

回答

2

懲戒和相同的調用的存根需要一起發生(無論是在giventhen塊):

... 
then: 
1 * bundle.getName() >> "name" 
1 * bundle.getVersion() >> "1.0.0" 
x == "name: 1.0.0" 

Spock Reference DocumentationCombining Mocking and Stubbing更詳細地解釋這一點。

另一種方法是擺脫模擬部分(1 * bundle.getName()等),這可能不是所有必要/有幫助的。

+0

在這種情況下,我不能夠有一個共同的嘲笑,這是由多個測試方法使用。例如,在「設置」方法中創建模擬交互,然後在多種測試方法中進行存根。我對嗎? – mhshams

+2

你是對的,你只能覆蓋整個交互(並且必須發生在'then'塊中)。你不能更早地聲明模擬部分和稍後聲明模擬部分(對於同一個交互)。 –