我想使用spock来查找是否调用了类中的方法。但是当我尝试验证它时,when块表示该方法从未被调用过。
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;
}
public class PaymentMethod {
public void debit(Integer amount) {
// TODO
}
public void credit(Integer amount) {
// TODO
}
}
import spock.lang.Specification
import spock.lang.Subject
class BillSpec extends Specification {
@Subject
def bill = new Bill(100)
def "Test if charge calculated"() {
given:
PaymentMethod method = Mock()
when:
bill.pay(method)
then:
1 * method.debit(100)
// 1 * bill.calculateTaxes() // Fails with (0 invocations) error
0 * _
}
}
在上面的示例中,我想要做的是验证是否正在调用calculateTaxes,但测试失败(0调用)。我尝试使用间谍但不确定因为Bill采用参数化构造函数会是什么语法。
当你像这样窥探calculateTaxes()
实例时,你可以测试Bill
调用:
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)