【问题标题】:How to mock method calls of mock objects?如何模拟模拟对象的方法调用?
【发布时间】:2015-04-25 10:22:40
【问题描述】:

考虑这个例子

    resp.getWriter().write(Collections.singletonMap("path", file.getAbsolutePath()).toString());

其中respHttpServletResponse 并被模拟。

我正在使用 JMock Mockery 来模拟这些

我的代码看起来像

   try {
          atLeast(1).of(resp).getWriter().write(String.valueOf(any(String.class)));
        } catch (IOException e) {
          e.printStackTrace();
        }
        will(returnValue("Hello"));

当我运行它时,我得到了

java.lang.NullPointerException

我相信这是因为 getWriter() 没有发回任何东西

我该如何处理这种情况?

【问题讨论】:

  • 只是你的模拟的 getWriter() 应该返回一个作家的模拟

标签: java unit-testing junit mockito jmock


【解决方案1】:

您需要 2 个模拟对象。

HttpServletResponse resp = context.mock(HttpServletResponse.class);
Writer writer = context.mock(Writer.class);

...

atLeast(1).of(resp).getWriter();
will(returnValue(writer));
allowing(writer).write(with(any(String.class));

【讨论】:

    【解决方案2】:

    我不会对Writer 使用模拟。您想测试输出是否被写入,而不是导致输出被写入的交互。

    改为使用真实的对象:

    HttpServletResponse mockResponse
        = context.mock(HttpServletResponse.class);
    StringWriter writer = new StringWriter();
    

    ...

    atLeast(1).of(mockResponse).getWriter();
    will(returnValue(writer));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      相关资源
      最近更新 更多