【问题标题】:How to mock private getters? [duplicate]如何模拟私人吸气剂? [复制]
【发布时间】:2015-05-14 00:53:27
【问题描述】:

我有一个要测试的课程。它看起来像这样:

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

我该怎么做?

【问题讨论】:

  • 它完全不同,可以保持开放,IMO
  • @NickJ:我不太相信。建议通常是相同的:不要这样做,使用不同的方法来注入这些依赖项,等等。

标签: java jmockit


【解决方案1】:

非常简单,无需mock私有方法或更改被测类:

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

【讨论】:

    【解决方案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);
    

    【讨论】:

    • Dependency 的创建可能非常昂贵,并且可能永远不会被使用。所以失去懒惰的创造可能是不可取的。
    • 在这种情况下,很容易改为传入 DependencyFactory
    猜你喜欢
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 2023-02-02
    • 2020-11-20
    • 2018-10-13
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多