考虑这个例子
resp.getWriter().write(Collections.singletonMap("path", file.getAbsolutePath()).toString());
其中 resp
是 HttpServletResponse
并且被模拟。
我正在使用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/