使用Spock验证非间谍方法调用

时间:2019-03-21 08:55:57

标签: 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();
        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使用参数化构造函数,因此不确定语法是什么。

1 个答案:

答案 0 :(得分:3)

像这样监视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)

结果如下: enter image description here

相关问题