本文介绍了如何模拟接口Java PowerMockito的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟一个界面。

I m trying to mock an interface.

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

}

在我的代码中,我将此方法称为 findByAppli ,我想返回一个FlowCopyParams列表。

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);
}  

我有这个错误:

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

我不知道为什么因为方法findByAppli必须有两个字符串参数,我把 Mockito。 anyString(),我仍然有 IllegalArgumentException

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

任何线索?

Thxs。

推荐答案

您不需要使用PowerMockito,并且作为其接口,theres不需要spy(),因为你不依赖于任何非模拟逻辑。

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;

@Before 带注释的方法中:

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

然后在测试中参考 flowCopyParamsBusinessManagerMock

这篇关于如何模拟接口Java PowerMockito的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 08:25