统计方法变量实例的方法调用

Count method invocation of method variable instance

我有一些这样的代码:

class FooBar {
    private String stateFoo;

    public FooBar(String stateFoo){
        this.stateFoo = stateFoo;
    }        

    public void foo() {
        FooInst f = FooInstFactory.createSomeFooInst(AnotherStaticFooConfig.getSomePath);
        f.justCountMe();
    }
}

我的目标是确保 f.justCountMe() 只执行一次。我知道如何用 mockito 来做这件事。 我不知道的是如何将 FooInst 的模拟版本注入 foo 方法?这样我就可以计算调用次数了?

甚至可以这样做吗?

您需要使用 powermockito 和模拟静态方法。请在此处查看如何执行此操作的说明

PowerMockito mock single static method and return object

如果可能的话;我建议避免使用调和静态字段的模拟库(以 PowerMock/Mockito 的方式)——因为它通常会带来不良副作用(例如,许多 "coverage" 工具在发生静态模拟时会产生无效结果).

所以我的建议是:重新设计你的 class 测试。而不是从静态工厂获取 f;为工厂或 f 提供构造函数;然后你可以模拟相应的对象;无需求助于强大但危险的 "Powerxyz" 东西。