【发布时间】:2021-02-19 16:28:32
【问题描述】:
我试图避免在这里使用 PowerMockito。我们有遗留代码,其中包含静态和无效的方法,并且有需要模拟它们的测试。有没有办法做到这一点,或者重构遗留代码是这里的唯一方法?
class MySample {
public static void sampleMethod(String argument){
//do something
}
}
如果我使用通用的 MockStatic 语法,它会要求我返回一些内容:
MockedStatic <MySample> sampleMock = Mockito.mockStatic( MySample.class );
sampleMock.when(() -> MySample.sampleMethod(Mockito.any(String.class)));
例外:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.mytests.Test.setMock(Test.java:35)
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, which is not supported
3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed
编辑:请注意,我希望模拟一个既是静态又是 void 的方法。
【问题讨论】:
-
这能回答你的问题吗? How to mock static method without powermock
-
感谢您的回答,但引用的示例不适用于 void 方法。
-
@Slaw 该问题中接受的答案希望我们有一个实例,但这里的测试方法是静态的。有没有静态和无效方法的示例?