How to mock An Interface Java PowerMockito

与世无争的帅哥 提交于 2019-12-05 05:48:51

You don't need to use PowerMockito, and as its an Interface, theres no need to spy() as you are not relying on any non mocked logic.

It can be done like this, in your test class define a class variable.

private FlowCopyParamsBusinessManager flowCopyParamsBusinessManagerMock;

In an @Before annotated method:

flowCopyParamsBusinessManagerMock = Mockito.mock(FlowCopyParamsBusinessManager.class);
List<FlowCopyParams> flowCopyParamsList = new ArrayList<>();
when(flowCopyParamsBusinessManagerMock 
.findByAppli(Mockito.anyString(), Mockito.anyString()).thenReturn(flowCopyParamsList);

Then refer to flowCopyParamsBusinessManagerMock in your tests.

My test did not work because I was trying to spy the class and not on the instance of FlowCopyParamsBusinessManager.class .

First , we have to create the mock :

FlowCopyParamsBusinessManager mockFlowCopyParamsBusinessManager = PowerMockito.mock(FlowCopyParamsBusinessManager.class);

Then , spy the instance :

PowerMockito.spy(mockFlowCopyParamsBusinessManager);
PowerMockito.when(mockFlowCopyParamsBusinessManager, "findByAppli", Mockito.anyString(), Mockito.anyString()).thenReturn(flowCopyParamsList);

It works as well !

I did this put this @RunWith(PowerMockRunner.class) at the top of the class. then mock Object with PowerMockito.mock(MyMock.class); This way use can mock a interface or final class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!