繁体   English   中英

从正在测试的类中模拟一个单独的类函数

[英]Mocking a separate class function from the class that is being tested

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

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 对象。

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

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

这是行不通的,因为Caller没有注入到functionToBeTested函数中。

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

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

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

有关此处的第二种方法的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM