Issue
I do have question, about using mockito. Let's assume I have following method chain which I need to mock.
mockHeroFacade.getHero().getItems().getSword().getId()
, so what my tested method need to is only Id
of Sword
object.
Until know, whenever I had this kind of chain I had two different approaches.
- Is to mock
@Mock HeroFacade mockHeroFacade
andwhen(mockHeroFacade.getHero()).thenReturn(createFullHero())
, so what createFullHero is returning is full Hero object with Items object, which cointains Sword object which contains its ID. And this is ok, but if object would be bigger it would take some time - Is to mock every object seperatly not only
HeroFacade
.
As seen below
class TestHero {
@Mock
HeroFacade mockHeroFacade;
@Mock
Hero mockHero;
@Mock
Items mockItems;
@Mock
Sword mockSword;
@Before
public void setup(){
when(mockHeroFacade.getHero()).thenReturn(mockHero);
when(mockHero.getItems()).thenReturn(mockItems);
when(mockItems.getSword()).thenReturn(mockSword);
when(mockItems.getId()).thenReturn(100000);
}
}
And this approach is also working, but still, could be bothersome, to write a lot of code.
And I am wondering if I could go on shortcut and do something like:
when(mockHeroFacade.getHero().getItems().getSword().getId()).thenReturn(10000)
Solution
I was able to find out the answer.
It is possible to use RETURNS_DEEP_STUBS
, which tells mockito to make deep mocks.
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private MockHeroFacade mockHeroFacade;
This enable you to make chain call.
Answered By - Suule
Answer Checked By - Katrina (JavaFixing Volunteer)