Mocking methods of local scope objects with Mockito

Viewed 143300

I need some help with this:

Example:

void method1{
    MyObject obj1=new MyObject();
    obj1.method1();
}

I want to mock obj1.method1() in my test but to be transparent so I don't want make and change of code. Is there any way to do this in Mockito?

7 Answers

If you don't prefer to use PowerMock, you may try the below way:

public class Example{
...
void method1(){
    MyObject obj1 = getMyObject();
    obj1.doSomething();
}

protected MyObject getMyObject(){
    return new MyObject();
}
...
}

Write your test like this:

@Mock
MyObject mockMyObject;

@Test
void testMethod1(){
    Example spyExample = spy(new Example());
    when(spyExample.getMyObject()).thenReturn(mockMyObject);
    //stub if required
    doNothing().when(mockMyObject.doSomething());
    verify(mockMyObject).doSomething();
}

Both mocking of a new instance creation and static methods is possible without PowerMock in the latest mockito versions and junit5.

Take a look in the methods Mockito.mockConstruction() and Mockito.mockStatic().

In your case:

try (MockedConstruction<MyObject> myobjectMockedConstruction = Mockito.mockConstruction(MyObject.class,
        (mock, context) -> {
            given(mock.method1()).willReturn("some result"); //any additional mocking
        })) {
    underTest.method1();
    assertThat(myobjectMockedConstruction.constructed()).hasSize(1);
    MyObject mock = myobjectMockedConstruction.constructed().get(0);
    verify(mock).method1();
}
Related