Mockito没有嘲笑电话 [英] Mockito is not mocking a call

查看:77
本文介绍了Mockito没有嘲笑电话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试的功能之一是装入机器.我想模拟ping方法,该方法实际上试图将ssh装入计算机,因为我并不是真正地将其装入计算机.

One of the functions I'm testing is sshing into a machine. I want to mock the ping method, that actually tries to ssh into a machine, since I am not really sshing into a machine.

我正在测试的课程:

public class TestMachine {
    public int ping(host){
    }

    public boolean machineIsGood(host) {
        blah blah
        int val = ping(host);
        blah blah blah
        if(val != 0) return false;
        return true;
    }
}

测试类如下:

public class TestClass {
    public void setUp() {
        TestMachine tester = spy(new TestMachine());
    }

    public void testOne() {
         when(test.ping(anyString()).thenReturn(-1);
         assertFalse(tester.machineIsGood("testHost"));
    }
{

问题是,当我在本地运行它们时,它们工作得很好,但是在我们的自动构建系统上,似乎实际上是在调用真正的ping并获取身份验证异常. 因为我已经读过它有点怪异,所以我将使用模拟()而不是间谍(),但我只是不明白在实际调用方法方面有什么不同!只是想知道其他人是否有任何见识.

The problem is that when I am running them locally, they work just fine, but on our autobuild system it seems like it is actually calling the real ping and getting an Authentication Exception. I'm going to use mock() instead of spy() since I've read it's a bit weird, but I just can't understand what makes a difference in that it is actually calling the method! Just wondering if anyone else has any insight.

推荐答案

public class TestClass {
  private TestMachine tester;
  public void setUp() {         
    tester = mock(TestMachine.class);     
  }      

  public void testOne() {
          when(tester.ping(anyString()).thenReturn(-1);
          assertFalse(tester.machineIsGood("testHost"));
     }
} 

这篇关于Mockito没有嘲笑电话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆