'Can I mock only one method instead of every object?

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.

  1. Is to mock @Mock HeroFacade mockHeroFacade and when(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
  2. 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 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Suule