如何使用Spy模拟部分方法

时间:2018-05-18 03:56:55

标签: java unit-testing spring-boot mockito junit4

我正在我的项目中进行单元测试。

我写了一个测试脚本来测试一个带有间谍的类,我用" Mockito.doReturn"来模拟一个方法。但似乎并没有对我嘲笑的那种方法起作用。

在我的测试用例中,我模拟了syncLogs()并将返回值设置为" false"。因此," syncLogs()"不应该被执行,返回值必须是" false"。

实际上,我嘲笑的syncLogs()仍然被执行,返回值是" true"。我不知道为什么模拟在我的测试中不起作用。

有人有任何想法或遇到这个问题吗?

class ApplicationTest{

public void testCase2() {
    setArgs(new String[] {"2018-04-23 00:08:00", "2018-04-23 00:10:00", "" });
    String startTime = "2018-04-23 00:08:00";
    String endTime = "2018-04-23 00:10:00";
    StringBuilder message = new StringBuilder();
    ApplicationCmdLine spy = Mockito.spy(ApplicationCmdLine.class);

    Mockito.doReturn(false).when(spy).syncLogs(startTime, endTime, message);
    TestCase.assertEquals(true, spy.manualSyncProess(getArgs()));
  }
}

class ApplicationCmdLine {

public boolean manualSyncProess(String[] args){...
   String information;
   if(!syncLog(.....))
      printUsageMessage(information);
}
public void printUsageMessage(StringBuilder message){
   System.out.println(message);
}
public boolean syncLogs(String startTime, String endTime, StringBuilder message) {....}

}

感谢您的帮助:)。

0 个答案:

没有答案