我可以模拟 juni5 和 mockito 或 easymock 的静态方法吗?

Can i mock static method whith juni5 and mockito or easymock?

我需要用 junit5 (这很重要) 和 mockito 或 easymock 模拟一个静态方法。 我看到 powermock 只适用于 junit 4。 有任何形式可以用 junit5 做吗?

据我所知不是。最简单的方法是用 non-static 方法屏蔽它。

public class A {
    void foo() {
        Stuff s = MyClass.getStuff();
    }
}

会变成

public class A {
    private final StuffProxy stuffProxy;
    public A(StuffProxy stuffProxy) {
        this.stuffProxy = stuffProxy;
    }
    public A() {
        this(new StuffProxy());
    }
    void foo() {
        Stuff s = stuffProxy.get();
    }
}

public class StuffProxy {
    public Stuff get() {
        return MyClass.getStuff();
    }
}

那你嘲笑StuffProxy.

如果没有 PowerMock,静态方法的模拟是不可能的。当您需要 PowerMock 时,这意味着代码没有以可测试的方式正确开发。我正在使用 Java 11、JUnit 5 和 Mockito 开发一个项目。 PowerMock 根本不支持这个。我怀疑它会永远支持它。

话虽这么说:使其可测试的唯一方法是将 class-with-static-method 注入到您需要测试的 class 中,然后替换 [=17 中的 bean 的实现=] 与模拟。当你注入它时,你就有了一个活动对象,所以不再需要静态方法了。

更改代码和使用注入框架(如Spring)有好处。我知道有些情况你不能这样做。如果你真的不能改变实现,就让它保持原样并进行大量单元测试以使用各种参数单独测试静态方法。只是为了确保此 class 按预期工作。