有没有一些方法不能被 Mockito 嘲笑而不调用该方法?



我是Mockito的新手,并认为这是嘲笑的摇滚。我刚刚遇到了似乎无法使它起作用的情况 - 存在,用模拟方法代替普通对象的方法,没有> 当我尝试模拟它时被调用的方法。

这是我要做的事情的超级简化示例,可悲的是,这并没有复制错误,但似乎与我的真实代码完全相同。

public class SimpleTest
{
    public class A
    {
    }
    public class B
    {
      public int getResult(A anObj)
      {
           throw new RuntimeException("big problem");
      }
    }
    @Test
    public void testEz()
    {
      B b = new B();
      B spy = spy(b);
      // Here are both of my attempts at mocking the "getResult" method. Both
      // fail, and throw the exception automatically.
      // Attempt 1: Fails with exception
      //when(spy.getResult((A)anyObject())).thenReturn(10);
      // Attempt 2: In my real code, fails with exception from getResult method
      // when doReturn is called. In this simplified example code, it doesn't ;-(
      doReturn(10).when(spy).getResult(null);
      int r = spy.getResult(null);
      assert(r == 10);
    }
}

因此,当前我运行测试时,测试会在我尝试嘲笑间谍的" getResult"方法时通过抛出异常而失败。例外是我自己的代码的例外(即运行时例外),当我尝试模拟" getResult"方法= ie时,它会发生。

请注意,我的真实用例当然更复杂..." B"类还有我想离开的许多其他方法,只需模拟一种方法。

所以我的问题是如何模拟它,以便该方法未调用?

主要注意:我只是从头开始重写整个测试,现在正常工作。我确定我的某个地方有一个错误,但是现在不存在 - 当使用间谍被嘲笑时,该方法没有调用!就其价值而言,我在模拟该方法时使用了doreturn语法。

doReturn(10).when(spy).getResult(null);

您的重新编辑问题现在可以正常工作。

此评论的行是错误的

when(spy.getResult((A)anyObject())).thenReturn(10);

应该是

when(spy.getResult(any(A.class))).thenReturn(10);

完整测试(未调用方法)

public class SimpleTest {
    public class A {
    }
    public class B {
        public int getResult(A anObj) {
            throw new RuntimeException("big problem");
        }
    }
    @Test
    public void testEz() throws Exception {
        B b = new B();
        B spy = spy(b);
        doReturn(10).when(spy).getResult(null);
        int r = spy.getResult(null);
        assert (r == 10);
    }
}

结果

Tests Passed: 1 passed in 0,176 s

最新更新