问题描述
我需要模拟 apache.commons.io.IOUtils 类的 toByteArray().我有一个这样的代码片段:
I need to mock toByteArray() of apache.commons.io.IOUtils class.I've a code snippet like ths:
PowerMockito.mockStatic(IOUtils.class);
PowerMockito.when(IOUtils.toByteArray(any(InputStream.class))).thenReturn(mockByteArray);
但是我从 org.apache.commons.io.IOUtils.copyLarge() 函数得到 NullPointerException.
But I'm getting NullPointerException from org.apache.commons.io.IOUtils.copyLarge() function.
推荐答案
看起来方法没有被模拟,而是调用了真正的方法.
It looks like the method is not mocked and the real method is called instead.
PowerMock 使用可以模拟静态方法的特殊测试运行器.
PowerMock uses special test runner that can mock static methods.
将 @RunWith(PowerMockRunner.class)
和 @PrepareForTest(IOUtils.class)
注释放在您的测试类上.
Put @RunWith(PowerMockRunner.class)
and @PrepareForTest(IOUtils.class)
annotations on your test class.
参见文档
这篇关于模拟 apache.commons.io.IOUtils 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!