【问题标题】:Mocking a method inside another method called without using class object在不使用类对象的情况下模拟另一个方法中的方法
【发布时间】:2023-03-24 16:28:01
【问题描述】:

我试图模拟一个方法,从另一个方法调用而不使用类对象。在指定的代码中,我想模拟methodA(),即调用methodB(),而不使用对象。

我无法更改现有课程中的任何内容。

class A{

public String methodA(){
//do something
String s = methodB(employee);
}

public String methodB(Employee e){
 e.getId();
}
}

我已经尝试过:

  1. Mockito.doReturn("id").when(objectOfA).methodB(employee);
  2. when(methodB(employee)).thenReturn("id");

【问题讨论】:

  • A 类正在测试中?你想模拟methodA()。这是正确的@Abhi
  • 是的 A 类正在测试中。我想通过模拟 methodB() 来测试 methodA()

标签: java junit mocking mockito


【解决方案1】:
A a = mock(A.class);
when(a.methodA()).thenReturn("Whatever you want");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2017-02-21
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    相关资源
    最近更新 更多