【问题标题】:How to stubb a private method call of my tested class如何存根我的测试类的私有方法调用
【发布时间】:2019-12-10 03:24:34
【问题描述】:

我实际上是在尝试测试一个需要数据库连接的方法(我目前无法实现),所以我想测试忽略数据库连接的方法。

@Test
public void Test(){
         ExampleClass ex = new ExampleClass();

         ex.methodA();
}

我的方法正在调用一个内部类,而该类正在调用破坏我的测试的私有方法。我实际上不能调用 Tested 类的私有方法,因为它是不可见的。

public class ExampleClass{

      public methodA(){
                    .......
                    return new innerClass();
      }

         private class innerClas{
            public methodB(){
                             ..........
                              ..........
                              Object a = send(....); //This is my DB Connections that crashes.
            }

            private send(....){
                       .......... 
                         .........
            }
         }
}

我需要忽略Tested类的Send方法,因为有DB Connection。如果我可以存根发送,忽略它就足够了。

【问题讨论】:

  • 对象 a 在方法 B 处创建。
  • 你不能在真正的 Mockito 中使用带有 private 方法的部分模拟/间谍,你需要 PowerMockito 来做到这一点。但要小心,这不是你想轻易购买的依赖项。

标签: java eclipse testing junit mockito


【解决方案1】:

不要在ExampleClass#methodA() 中创建innerClass 的对象。而是通过构造函数或方法将此对象注入ExampleClass

现在,使用 Mockito 或等效工具从测试类模拟 innerClass 并从您希望避免调用真实内容的目标方法返回模拟结果。

顺便说一下私有方法模拟使用PoweMock,添加如下注解:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ExampleClass.class)
public class MyTest{
}

【讨论】:

  • 它的遗留代码,我实际上是在做测试,我不能改变代码:(
  • 我明白了。您要测试哪种方法?我看到methodB() call`send()` 但是,测试只调用methodA()。我假设methodB()send() 都属于innerClass,对吗?除非你不能使用innerClass 的模拟实例,否则你不能阻止来自send() 的数据库调用。顺便说一句,而不是调用methodA() 来获取innerClass 对象,为什么不直接创建innerClassmock 实例?请使您的示例的语法正确。
  • 抱歉语法错误。是的,你的假设是对的。我应该如何模拟那个私有的 innedClass?
  • 我假设您正在尝试使用 innerClass#methodB() 并模拟 innerClass#send()。要模拟私有方法 innerClass#send() 使用答案中提到的 PowerMock 。我会用你的例子更新答案。
  • 你能澄清一件事吗 - 你如何从你的测试中调用 methodB() (即使没有模拟),因为你将 innerClass 声明为私有的?你甚至不能从外部引用 InnerClass。那么如何从 ExampleClass 之外调用 mnethodB() 呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多