PowerMockito测试私有void方法报错UnfinishedStubbingException

2022-07-16 09:35:35

待测试代码片段:

classPowerMockitoExample{privatevoidTestPrivateMethod(){
    System.out.println("Inside private method");}publicvoidTestPublicMethod(){
    System.out.println("Inside public method");TestPrivateMethod();}}

创建测试Test类:

@RunWith(PowerMockRunner.class)publicclassPowerMockitoExampleTest{@Testpublicvoidtest()throws Exception{

 PowerMockitoExample testclass= PowerMockito.spy(newPowerMockitoExample());
 PowerMockito.doNothing().when(testclass,"TestPrivateMethod");
 testclass.TestPublicMethod();}

运行后报错:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:-> at...

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. missingthenReturn()2. you are trying to stub afinal method, which is not supported3: you are stubbing the behaviour of another mock inside before'thenReturn' instruction is completed


at...

解决:
除了要PowerMockito.spy()对象以外
还必须在@RunWith批注之后使用@PrepareForTest添加类名称!!!

@RunWith(PowerMockRunner.class)@PrepareForTest({PowerMockitoExample.class, xxx.class})publicclassPowerMockitoExampleTest{...}
  • 作者:ReaganZhuu
  • 原文链接:https://blog.csdn.net/qq_44543551/article/details/115351666
    更新时间:2022-07-16 09:35:35