powermock

Posted

tags:

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

mock静态方法

@RunWith(PowerMockRunner.class)
@PrepareForTest({CaseAction.class, OssUtil.class})

PowerMockito.mockStatic(OssUtil.class);
PowerMockito.when(OssUtil.class,"deleteFile",Mockito.anyString(),Mockito.anyInt()).thenReturn(true);

mockHttpServletResponse,获取response输出

//mock response
MockHttpServletResponse response = new MockHttpServletResponse();
caseAction.doDeleteAccessory("a/b", "c.txt", 1000, 1, response);

byte[] content = response.getContentAsByteArray();
Assert.assertEquals("{\"errMsg\":\"\",\"result\":\"{\\\"id\\\":\\\"1\\\",\\\"status\\\":\\\"ok\\\"}\"}",new String(content,"GB2312"));

 mock内部创建对象方法的调用

ParseContext parseContext = PowerMockito.mock(ParseContext.class);
PowerMockito.whenNew(ParseContext.class).withAnyArguments().thenReturn(parseContext);
TreeNode treeNode = new TreeNode();
treeNode.setName("case1");
PowerMockito.when(parseContext.parser()).thenReturn(treeNode);

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

PowerMock学习之Verifying的使用

PowerMock ECLemma 覆盖问题

PowerMock+Junit测试小记

PowerMock学习之Mock Final的使用

PowerMock 有啥好的替代品吗?

Mockito与PowerMock的使用基础教程