我在这里试图避免使用PowerMockito。我们有遗留代码,其中包含既是静态的又是void的方法,并且有需要模拟它们的测试。是否有一种方法可以做到这一点,或者改造遗留代码是唯一的方式?
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的方法。