How to mock An Interface Java PowerMockito

删除回忆录丶 提交于 2019-12-22 05:06:15

问题


I m trying to mock an interface.

public interface FlowCopyParamsBusinessManager {
List<FlowCopyParams> findByAppli(String application, String sourcePattern)
        throws FlowCopyParamsBusinessException;

}

In my code, when i call this method findByAppli, i would like to return a list of FlowCopyParams.

List<FlowCopyParams> lstFlowCopyParams = flowCopyParamsBusinessManager.findByAppli(
                    "TOTO","TATA);

Here my try in the class test:

@BeforeClass
public static void mockBeanIn() throws Exception {
List<FlowCopyParams> flowCopyParamsList = new ArrayList<>();

PowerMockito.spy(FlowCopyParamsBusinessManager.class);
PowerMockito.when(FlowCopyParamsBusinessManager.class, "findByAppli",  Mockito.anyString(), Mockito.anyString()).thenReturn(flowCopyParamsList);
}  

I have this error :

java.lang.IllegalArgumentException: object is not an instance of declaring class

I don't know why because the method findByAppli must have two string parameters, and i put Mockito.anyString() and i still have IllegalArgumentException.

Any clue ?

Thxs.


回答1:


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.




回答2:


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 !




回答3:


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.



来源:https://stackoverflow.com/questions/39267199/how-to-mock-an-interface-java-powermockito

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