java - 如何模拟模拟对象的方法调用?

标签 java unit-testing junit mockito jmock

考虑这个例子

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

其中 respHttpServletResponse 并且被模拟。

我正在使用JMock Mockery mock 这些

我的代码看起来像

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

当我运行这个时,我得到

java.lang.NullPointerException

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

我该如何处理这种情况?

最佳答案

您需要 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));

关于java - 如何模拟模拟对象的方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29785589/

相关文章:

javascript - 如何解释 BusterJS 测试路径中的通配符?

java - 根据参数获取失败的测试用例数

java - RuntimeExtension.class—— ".class"是什么意思?

java - 我如何测试接口(interface)?

java - 用 Java 计算一系列?

java - 数学表达式到java方法?

unit-testing - 如果使用私有(private)访问器,针对 3.5 框架的 VS2010 SP1 单元测试会失败

java - Mockito:如果传递给 mock 的参数被修改了怎么办?

java - Android:调用 EditText getText() 方法时出现 NullPointerException

java - 如何使第一列增长,而所有其他列在 MigLayout 中具有最小尺寸?