PowerMock

Posted chen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PowerMock相关的知识,希望对你有一定的参考价值。

触发时第一次返回v1,后续都返回v2:
Mockito.when(methodCall).thenReturn(value1).thenReturn(value2)

spy调用真实对象: mock调用的是假的方法,即null,方法体为空的
使用when()依然会调原来的方法执行
doReturn("spy!").when(xx).getXX(); 输出spy!
when(spy.service()).thenReturn("spy!"); 输出invoked!spy!
ps: 使用PowerMock反射执行还是会执行原来方法

模拟抛出异常: thenThrow()

mock同一类方法:
Personp=newPerson();
Personp2=Mockito.spy(p);
Mockito.doReturn("3333").when(p2).getName2();
System.out.println(p2.getName());

适用于无返回值,跳过当前方法:
doNothing()
PowerMockito.doNothing().when(xx.class,"writeFiles",any());

静态方法: powermock
注意: powermock只能再jdk8用,请idea给test配置jdk8(jdk11亲测无效)
@PrepareForTest -> 加入需要模拟的静态类
PowerMockito.mockStatic(String.class);
when(String.format(any(),any(),any())).thenReturn("abcdefg");

powermock构造函数,new:
注意!preparefortest加入被测试的类而不是whennew的类
@PrepareForTest({x.class})
@Rule
public PowerMockRule rule = new PowerMockRule();
PowerMockito.whenNew(File.class).withArguments(any()).thenReturn(newFile);

静态内部抽象类:
FileTransformer.SheetHandler sh = spy(FileTransformer.SheetHandler.class);

FileProcessor.FileDescription fileDescription = new FileProcessor.FileDescription();

PowerMock private void method:
xx spy = PowerMockito.spy(target);
PowerMockito.doNothing().when(spy, "processUploadSuccess",any(),any());

注意使用powermockito.spy()
WidgetContainer widget = mock(WidgetContainer.class);
xx spy = PowerMockito.spy(target);
PowerMockito.doReturn(widget).when(spy,"yy");

PowerMock static void:
PowerMockito.mockStatic(FileUtils.class);
PowerMockito.doNothing().when(FileUtils.class,"forceMkdir",file);

mock extend:
ReflectUtil.setField(target, "logger", mock(Logger.class), AbstractHandler.class);

以上是关于PowerMock的主要内容,如果未能解决你的问题,请参考以下文章