如何模拟私人吸气剂?

How to mock private getters?

我有一个 class 想要测试。它看起来类似于:

public class ClassUnderTest
{
    private Dependency1 dep1;

    private Dependency1 getDependency1()
    {
       if (dep1 == null)
          dep1 = new Dependency1();
       return dep1;
     }

    public void methodUnderTest()
    {
       .... do something
       getDependency1().InvokeSomething(..);
    }
}

Class Dependency1 很复杂,我想在为 methodUnderTest().

编写单元测试时模拟它

我该怎么做?

我认为您的架构需要研究一下。

为什么不做这样的事情...

public class MyClass {

  private Dependency dependency;

  public void setDependency(Dependency dep) {
    this.dependency = dep;
  }

  public void myMethod() {
    Result result = dependency.callSomeMethod();
    //do stuff
  }
}

然后在生产中你可以这样做:

myClass.setDependency(realDependency);

在测试中,您可以:

myClass.setDependency(mockDependency);

非常简单,无需模拟私有方法或更改被测class:

@Test
public void exampleTest(@Mocked final Dependency dep) {
    // Record results for methods called on mocked dependencies, if needed:
    new Expectations() {{ dep.doSomething(); result = 123; }}

    new ClassUnderTest().methodUnderTest();

    // Verify another method was called, if desired:
    new Verifications() {{ dep.doSomethingElse(); }}
}