2013-02-19 130 views
3

假設我有一種方法將一些數據填充到列表中,並在內部調用另一個方法(我正在獨立測試),並將一些數據填充到列表。這裏最好的測試方式是什麼?如何爲調用其他方法的方法編寫spock測試用例

如何測試外部方法?我是否也應該從內部方法檢查數據,否則只測試由外部方法填充的數據是否正常?

回答

5

鑑於測試下面的類:

 
class MyTestClass { 
    int getAPlusB() { return getA() + getB() } 
    int getA() { return 1 } 
    int getB() { return 2 } 
} 

我可以寫出如下斯波克測試,以檢查該算法是正確的,而且還getA()getB()實際上是由getAPlusB()稱爲:

def "test using all methods"() { 
    given: MyTestClass thing = Spy(MyTestClass) 
    when: def answer = thing.getAPlusB() 
    then: 1 * thing.getA() 
      1 * thing.getB() 
      answer == 3 
} 

到目前爲止,這是運行所有3種方法的所有代碼 - getA和getB被驗證爲被調用,但實際上正在執行那些方法中的代碼。在你的情況下,你正在單獨地測試內部方法,並且在本次測試中你根本不想打電話給他們。通過使用spock間諜,你可以實例化一個真正被測試的類,但是可以選擇你想要指定返回值的特定方法:

def "test which stubs getA and getB"() { 
    given: MyTestClass thing = Spy(MyTestClass) 
    when: def answer = thing.getAPlusB() 
    then: 1 * thing.getA() >> 5 
      1 * thing.getB() >> 2 
      answer == 7 
} 
相關問題