使用 mockito 模拟嵌套方法调用 [英] mock nested method calls using mockito

查看:97
本文介绍了使用 mockito 模拟嵌套方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 4 个类,比如 A、B、C、D,每个类都调用另一个类的方法.

I have got 4 classes lets says A, B, C, D each calling on methods from another one.

现在我已经模拟了 A 类,并且想使用 mockito 模拟一个方法

now I have mocked class A, and want to mock a method using mockito

A a = Mockito.mock(A.class);

并希望在递归方法调用上获得foo",例如

and want to get "foo" on recursive method calls like

a.getB().getC().getD() 应该返回 "foo"

我试过了

when(a.getB().getC().getD()).thenReturn("foo");

when(a.getB().getC().getD()).thenReturn("foo");

但是得到了 nullPointerException

but got nullPointerException

然后我尝试了

doReturn("foo").when(a.getB().getC().getD());

doReturn("foo").when(a.getB().getC().getD());

然后我得到了 org.mockito.exceptions.misusing.UnfinishedStubingException:

我知道我可以创建 B、C 和 D 的对象,甚至可以编写类似

I know I can create objects of B, C and D, or can even write something like

B b = mock(B.class) 或 A.setB(new B())

B b = mock(B.class) or A.setB(new B())

等等.

但是我不能一次性完成吗?任何帮助将不胜感激.

But can't I do that in a single shot? Any help would be appreciated.

推荐答案

添加 RETURNS_DEEP_STUBS 成功了:

A a = Mockito.mock(A.class, Mockito.RETURNS_DEEP_STUBS);

这篇关于使用 mockito 模拟嵌套方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆