How to mock a local instance of a method with mockito Junit

java, junit, mockito

Solution

You need to use spy from Mockito 1.8 and mock only the method getBean

CertainBean bean = spy(new CertainBean());

when(bean.getBean()).thenReturn(yourInterfaceMockedBean);

there is more information about mocking real partial objects in this useful link: http://blog.javabien.net/2009/06/21/mockitos-partial-mocks-testing-real-objects-just-got-easier/

and here the changes on Mockito 1.8 https://code.google.com/p/mockito/wiki/ReleaseNotes#Changed_in_1.8.0_(23-07-2009)

Problem

I have the following method in the class CertainBean: ``` public boolean isOn() { InterfaceBean Bean = getBean(); return Bean.hasBeenSetOn(Param1, Param2); } ``` Now I would like to ``` assertEquals(CertainBeanInstance.isOn(),true); ``` In order to do that I need first to mock IntefaceBean. How can I do that? Thanks in advance

Original source