可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.