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

问题描述 投票:2回答:1

我想使用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采用参数化构造函数会是什么语法。

groovy java-8 mocking spock stub
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.