如何模仿私人吸气者?

时间:2015-05-13 13:58:24

标签: java jmockit

我有一个我想测试的课程。它看起来与此相似:

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()编写单元测试时嘲笑它。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

我认为您的架构需要关注。

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

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);

答案 1 :(得分:2)

这很容易,并且不需要模拟私有方法或更改被测试的类:

@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(); }}
}