【问题标题】:Are there some methods that can't be mocked by Mockito without the method being called on mock?如果没有在模拟上调用该方法,是否有一些方法无法被 Mockito 模拟?
【发布时间】:2014-01-22 20:06:25
【问题描述】:

我是 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”方法=即执行上面的“doReturn”行时。

请注意,我的实际用例当然更复杂......“B”类有很多其他方法,我想保留原样,只模拟一个方法。

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

主要注意事项:我刚刚从头开始重写了整个测试,现在可以正常工作了。我确定我在他们的某个地方有一个错误,但它现在不存在 - 使用间谍模拟时不会调用该方法!对于它的价值,我使用 doReturn 语法来模拟该方法。

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

【问题讨论】:

  • 嘿!测试要复杂得多,并且有很多特定领域的东西......但是失败的核心是那两条线“when ....”和“doReturn ....”线......但是根据您的经验, 有没有因为当你试图模拟它时该方法抛出异常而无法监视的方法?
  • when 的行肯定会抛出异常。但是doReturn 的行应该可以正常工作。这是做事的正确方法。您确定该方法不是final 或类似的东西吗?另外,这是getResult的唯一实现吗?
  • @BradParks 不,也许您应该添加在它不起作用时获得的堆栈跟踪。我还会确保在测试中使用了间谍(b 在你的问题中,而不是a
  • 感谢您的反馈。我将伪代码更新为真实代码,并且它可以工作。我的模拟方法不是最终的,但它确实有一个 @Context 参数。这是签名:public Response getResult(@Context HttpServletRequest request)。请注意,我在模拟和调用该方法时传入了 null。
  • 伪代码工作正常,添加真实代码 :) 请停止编辑这篇文章,因为我的回答是针对第一个版本 :) 彻底改变需要新问题。

标签: java unit-testing mockito


【解决方案1】:

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

这个注释行是错误的

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

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多