Mockito: mock instance method for all instances of a class

ddolce :

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!

Indra Basak :

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"));
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=431458&siteId=1