我们如何在不使用 power mockito 的情况下模拟私有方法

How can we mock private methods without using power mockito

我们可以在不使用 powermockito 的情况下模拟私有方法吗?我知道虽然 powermockito 是可能的,但只是想与所有人核实一下,是否可以通过其他方式实现。 谢谢 -山姆

根据设计,如果没有 PowerMockito 或类似工具,这是不可能的。

参见 Mockito's Wiki 他们给出了以下原因:

  1. It requires hacking of classloaders that is never bullet proof and it changes the API (you must use custom test runner, annotate the class, etc.).

  2. It is very easy to work around - just change the visibility of method from private to package-protected (or protected).

  3. It requires the team to spend time implementing & maintaining it. And it does not make sense given point (2) and a fact that it is already implemented in different tool (powermock).

  4. Finally... Mocking private methods is a hint that there is something wrong with Object Oriented understanding. In OO you want objects (or roles) to collaborate, not methods. Forget about pascal & procedural code. Think in objects.

当然有些情况是无法解决的,但退后一步

  1. 确保您正在测试正确的东西(您应该测试私有方法而不是 public 方法)
  2. 考虑将这些方法更改为包私有而不是依赖 PowerMock。

是的,我们可以为此使用 Java 供应商提供的反射 API。