如何为一个调用其他方法的方法编写一个spock测试用例

时间:2013-02-19 14:47:20

标签: testcase spock

假设我有一个方法将一些数据填充到列表中,它在内部调用另一个方法(我正在独立测试)并将一些数据填充到列表中。这里有什么最好的测试方法?

如何测试外部方法?我是否应该从内部方法检查数据,否则只测试外部方法填充的数据?

1 个答案:

答案 0 :(得分:5)

鉴于以下测试类:

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

我可以编写以下spock测试来检查算法是否正确,以及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 spy,您可以实例化正在测试的类的实例,但是可以选择存根要指定返回值的特定方法:

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
}
相关问题