我试图避免在这里使用 PowerMockito。我们有遗留代码,其中包含静态和无效的方法,并且有一些测试需要模拟它们。有没有办法做到这一点,或者重构遗留代码是唯一的方法吗?
class MySample {
public static void sampleMethod(String argument){
//do something
}
}
Run Code Online (Sandbox Code Playgroud)
如果我使用通用的 MockStatic 语法,它会要求我返回一些内容:
MockedStatic <MySample> sampleMock = Mockito.mockStatic( MySample.class );
sampleMock.when(() -> MySample.sampleMethod(Mockito.any(String.class)));
Run Code Online (Sandbox Code Playgroud)
例外:
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
Run Code Online (Sandbox Code Playgroud)
编辑:请注意,我正在寻找模拟一个既静态又无效的方法。
当模拟方法被调用时,您希望发生什么?
默认行为是什么也不发生。通过调用sampleMock.when(),您表明您希望将默认行为更改为其他行为。Mockito 正在抱怨,因为您没有随后调用 tothen___()来指定应该发生的情况。
我认为您可能希望发生一些不同的事情:
如前所述,这是默认行为,因此如果这就是您想要的,您只需删除第二行即可,它应该可以工作。但是,如果您确实需要进行调用when(例如用于参数捕获),您可以使用空来结束该行thenAnswer:
sampleMock.when(() -> MySample.sampleMethod(Mockito.any(String.class)))
.thenAnswer(invocation -> null);
Run Code Online (Sandbox Code Playgroud)
sampleMock.when(() -> MySample.sampleMethod(Mockito.any(String.class)))
.thenCallRealMethod();
Run Code Online (Sandbox Code Playgroud)
sampleMock.when(() -> MySample.sampleMethod(Mockito.any(String.class)))
.thenAnswer(invocation -> {
// insert code to do something else here
return null;
});
Run Code Online (Sandbox Code Playgroud)
sampleMock.when(() -> MySample.sampleMethod(Mockito.any(String.class)))
.thenThrow(RuntimeException.class);
Run Code Online (Sandbox Code Playgroud)
如前所述,默认行为是不执行任何操作,但我了解到还可以通过Answer在创建模拟时提供 来指定备用默认行为。例如,要让默认行为改为调用实际方法:
MockedStatic <MySample> sampleMock = Mockito.mockStatic( MySample.class, Mockito.CALLS_REAL_METHODS );
Run Code Online (Sandbox Code Playgroud)
但要注意 - 正如 Marc 在这个答案中指出的那样,即使您覆盖默认行为,真正的方法仍然会被调用!这可能会在未来得到修复;请参阅马克的回答以获得一些很好的参考