Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: mock instance method for all instances of a class

Tags:

I'm trying to stub an instance method of a particular class, so that when any instance of this Foo class calls this instance method doSomething, the same object is returned (see code below). However, mockito doesn't allow any matchers outside of verification or stubbing.

Bar object = new Bar();
given(any(Foo.class).doSomething(Arg.class)).willReturn(object);

And in Foo.class:

Bar doSomething(Arg param) {
    Bar bar = new Bar();
    // Do something with bar
    return bar;
}

Any way I can achieve this goal with Mockito? Thanks!

like image 873
ddolce Avatar asked Sep 12 '17 21:09

ddolce


1 Answers

You should use PowerMock if you want Foo to return the same instance of Bar when you call doSomething method on any instance of Foo. Here's an example:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)
public class FooMockAllInstanceTest {

    @Test
    public void testMockInstanceofObjectCreation() throws Exception {
        Bar mockBar = PowerMockito.mock(Bar.class);
        when(mockBar.sayHello()).thenReturn("Hi John!");
        PowerMockito.whenNew(Bar.class)
                .withNoArguments()
                .thenReturn(mockBar);

        Foo myFooOne = new Foo();
        assertEquals(mockBar,  myFooOne.doSomething("Jane"));

        Foo myFooTwo = new Foo();
        assertEquals(mockBar,  myFooTwo.doSomething("Sarah"));

        Baz bazOne = new Baz();
        assertEquals(mockBar, bazOne.doSomething("Sam"));

        Baz bazTwo = new Baz();
        assertEquals(mockBar, bazTwo.doSomething("Nina"));
    }
}

This example will return the same Bar object even when Baz is called. Here's the Baz class,

public class Baz {

    public Bar doSomething(String name) {
        Foo foo = new Foo();
        return foo.doSomething(name);
    }
}

Update 2

There's another slightly better way to test with PowerMock. Here it's,

@Test
public void testStubbingMethod() throws Exception {
    Bar mockBar = PowerMockito.mock(Bar.class);
    when(mockBar.sayHello()).thenReturn("Hi John!");

    PowerMockito.stub(PowerMockito.method(Foo.class, "doSomething",
            String.class)).toReturn(mockBar);

    Foo myFooOne = new Foo();
    assertEquals(mockBar, myFooOne.doSomething("Jane"));

    Foo myFooTwo = new Foo();
    assertEquals(mockBar, myFooTwo.doSomething("Sarah"));

    Baz bazOne = new Baz();
    assertEquals(mockBar, bazOne.doSomething("Sam"));

    Baz bazTwo = new Baz();
    assertEquals(mockBar, bazTwo.doSomething("Nina"));
}
like image 77
Indra Basak Avatar answered Sep 24 '22 16:09

Indra Basak