【发布时间】:2016-10-19 09:03:47
【问题描述】:
我有这段代码,我想用 powermockito 模拟:
long size = FileUtility.getFileFromPath(uri.getPath()).length())
这个静态方法的实现很简单:
public static File getFileFromPath(String filePath) {
return new File(filePath);
}
现在,当我在测试中编写这段代码时,测试失败了。
PowerMockito.mockStatic(FileUtility.class);
File fileMock = mock(File.class);
PowerMockito.when(FileUtility.getFileFromPath(anyString())).thenReturn(fileMock);
Mockito.doReturn(12).when(fileMock.length());
除了这个例外:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at nl.mijnverzekering.entities.declareren.NotaPdfMetadataTest.mockFileSize(NotaPdfMetadataTest.java:273)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
我以前见过这个错误(我应该将 mock(File.class) 提取到一个单独的变量中,就像我现在所做的那样)。 这里出了什么问题?是因为我使用模拟对象作为返回值吗?如何解决?
解决办法: 如果我将此方法添加到 FileUtility,我的测试当然会成功:
public static long getFileSizeFromFilePath(String filePath) {
return getFileFromPath(filePath).length();
}
然后简单
PowerMockito.mockStatic(FileUtility.class);
PowerMockito.when(FileUtility.getFileSizeFromFilePath(anyString())).thenReturn(size);
但我想阻止将那些不必要的方法列表添加到我的 FileUtility(并了解异常的原因)
【问题讨论】:
标签: mocking powermockito