【问题标题】:Mocking a separate class function from the class that is being tested从正在测试的类中模拟一个单独的类函数
【发布时间】:2020-01-07 13:55:41
【问题描述】:

我有一个函数正在调用另一个类的方法。此类和方法已经过测试,并且正在使用实时数据,这使得我的测试与我硬编码的预期值不一致。

public class MyClass{
  public void functionToBeTested(String params){
    //stuff to do
    Caller call = new Caller();
    callResult = call.post(someJSON);
    //do stuff with callResult
  }
}

这里是junit:

public class TestMyClass{
  MyClass testClass = new MyClass();
  Caller mock;

  @Before
  public void setup(){
  premadeAnswer = new String(file);
  mock = Mockito.mock(Caller.class);
  Mockito.when(mock.post(Mockito.any())).thenReturn(premadeAnswer);
  }

  @Test
  public void studentFees_CorrectSSN(){
    assertEquals(expected.getThing(), testClass.functionToBeTested("PARAMS").getThing());
  }
}

我很确定我做的一切都是正确的,但显然它不是在模拟,而是调用函数 ans 如果它不是一个 junit,它的行为就如预期那样。如果我不得不猜测发生了什么,即使我正在创建一个模拟对象并使用 when/thenReturn 它也没有附加到 MyClass testClass 对象。

【问题讨论】:

  • 您在方法中创建了一个新的 Caller 对象。因此,它与您的测试中的模拟对象不同。尝试使用 DI 将 Caller 对象注入到您的类中。或者创建一个方法 getCaller() 来返回新的 Caller 对象。然后你可以监视你的 CUT (MyClass) 并在调用 getCaller 时返回一个模拟。

标签: java unit-testing junit mocking mockito


【解决方案1】:

这不起作用,因为Caller 没有注入到functionToBeTested 函数中。

 Mockito.when(mock.post(Mockito.any())).thenReturn(premadeAnswer);

this when 语句仅适用于您的模拟实例,在 functionToBeTested 内,您正在创建 Caller 的新实例。

要么将functionToBeTested(String params) 更改为functionToBeTested(String params, Caller call),然后传递你模拟的Caller 实例,要么尝试模拟Caller 构造函数。

关于第二种方法的更多信息here

【讨论】:

    【解决方案2】:

    我注意到在您共享的第一个代码块中,没有指定返回值。我在下面的代码块中添加了void

    public class MyClass{
      public void functionToBeTested(String params){
        //stuff to do
        Caller call = new Caller();
        callResult = call.post(someJSON);
        //do stuff with callResult
      }
    }
    

    【讨论】:

    • 已修复
    猜你喜欢
    • 2017-05-12
    • 2014-03-30
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多