Groovy 使用Spock验证非间谍方法调用
我想使用spock来查找是否调用了类中的方法。但当我尝试验证它时,when块表示从未调用过该方法Groovy 使用Spock验证非间谍方法调用,groovy,java-8,mocking,spock,stub,Groovy,Java 8,Mocking,Spock,Stub,我想使用spock来查找是否调用了类中的方法。但当我尝试验证它时,when块表示从未调用过该方法 public class Bill { public Bill(Integer amount) { this.amount = amount; } public void pay(PaymentMethod method) { Integer finalAmount = amount + calculateTaxes(); m
public class Bill {
public Bill(Integer amount) {
this.amount = amount;
}
public void pay(PaymentMethod method) {
Integer finalAmount = amount + calculateTaxes();
method.debit(finalAmount);
}
private Integer calculateTaxes() {
return 0;
}
private final Integer amount;
}
在上面的示例中,我只想验证是否调用了calculateTaxes,但测试失败(0次调用)。我尝试使用spy,但不确定语法是什么,因为Bill采用了参数化构造函数。当您监视
Bill
实例时,您可以测试calculateTaxes()
调用,如下所示:
class SpyTestSpec extends Specification {
def "Test if charge calculated"() {
given:
def bill = Spy(new Bill(100))
PaymentMethod method = Mock()
when:
bill.pay(method)
then:
1 * method.debit(100)
1 * bill.calculateTaxes()
1 * bill.pay(method)
0 * _
}
}
另一件重要的事情是使calculateTaxes()
方法对测试可见,否则它仍然会失败:
public Integer calculateTaxes() { ... }
请注意,如果要测试未调用任何其他函数,则还应添加:
1 * bill.pay(method)
结果如下:
您是否将
calculateTaxes()
方法公开?看看屏幕截图,它真的很有效。
public Integer calculateTaxes() { ... }
1 * bill.pay(method)