使用Mockito模拟嵌套的方法调用 [英] mock nested method calls using 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,并且想要使用模拟方法模拟一个方法
now I have mocked class A, and want to mock a method using mockito
A a = Mockito.mock(A.class);
并希望在
a.getB().getC().getD()
应该返回"foo"
我尝试了
当(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.UnfinishedStubbingException:
我知道我可以创建B,C和D的对象,甚至可以编写类似
I know I can create objects of B, C and D, or can even write something like
B b =模拟(B.class)或A.setB(新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可以达到目的:
Adding RETURNS_DEEP_STUBS did the trick:
A a = Mockito.mock(A.class, Mockito.RETURNS_DEEP_STUBS);
这篇关于使用Mockito模拟嵌套的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!