我基本上有一个主类,它使用接口来调用包含成员的其他类。我应该模拟这个(具体的)主类用来调用其他类的接口。这样做的目的是为这些实现起来很麻烦的其他类创建一个模拟的getMember()方法。考虑到getMember()方法的某些返回值,我们现在只需要确保主类的行为符合预期。
我现在看到这种可能性的唯一方法是传递实现这些接口的类的模拟实例。
如果这似乎是一个愚蠢的问题,我很抱歉,但是我通过阅读这个作业,文档或通过搜索引擎找不到我的问题的答案。
答案 0 :(得分:3)
试试这个:
AnInterface anInterfaceMock = Mockito.mock(AnInterface.class);
//Set your properties here if you want return an specific object.
Member member = new Member();
Mockito.when(anInterfaceMock.getMember()).thenReturn(member);
YourMainClass yourMain = new YourMainClass();
yourMain.setAnInterfaceMock(anInterfaceMock);
yourMain.testMethod(); // call the method you wan to test. This method internal implementation is supposed to call anInterfaceMock.getMember()
Mockito.verify(anInterfaceMock).getMember();
<强>更新强> 在关于主类没有办法强制选择的界面进行模拟的信息之后,它似乎是PowerMockito的工作。但发布主类的代码会有很大帮助。
答案 1 :(得分:1)
它是您的主类创建其依赖项的实例(实现您提到的那些接口)吗? 如果可能,您最好更改主类以遵循依赖注入模式。然后,您将通过构造函数或通过setter为我们的主类提供其依赖项。这些依赖项可以是用于测试的模拟或生产代码中的真实实现。
稍微修改guilhermerama的例子。
YourMainClass yourMain = new YourMainClass(anInterfaceMock);