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!
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"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With