Reputation: 1118
I am trying to mock a method whatever the instance that calls this method is. As far as I could got reading this can't happen with Mockito and should be done with PowerMockito, but I can't figure out the way it should be done. I have
public class B{
public void veryAnnoyingMethod(int i, short s){}
}
public class A{
public void veryImportantMethod(){
B newB = new B();
newB.veryAnnoyingMethod(i,s);
...
}
}
I am trying to test the veryImportantMethod()
and want to mock the veryAnnoyingMethod()
.
I don't want to mock the constructor as explained here: Mocking methods of local scope objects with Mockito because apart from the veryAnnoyingMethod()
I need the newB
fully functional.
I have come up with something like:
B dummyB = PowerMockito.spy(new B());
PowerMockito.doReturn(null).when(dummyB.veryAnnoyingMethod(Mockito.anyInt(), Mockito.anyShort()));
But it throws exception, and I don't think it is what I actually need.
UPDATE
After a bit more reading it seems I have to use PowerMockito.stub
, or PowerMockito.supress
. So I have tried the following:
PowerMockito.stub(PowerMockito.method(B.class, "veryAnnoyingMethod", int.class, short.class)).toReturn(null);
or
PowerMockito.supress(PowerMockito.method(B.class, "veryAnnoyingMethod", int.class, short.class));
But with either the method is still executed
Upvotes: 5
Views: 6734
Reputation: 1118
OK, I finally got it to work. Using either of stub
and suppress
is working. The test looks something like this:
@RunWith(PowerMockRunner.class)
@PrepareForTest(B.class)
class TestClassAWithPowerMockito{
@Test
public void testVeryImportantMethod() throws Exception {
A a = new A();
PowerMockito.suppress(PowerMockito.method(B.class, "veryAnnoyingMethod", int.class, short.class));
a.veryImportantMethod();
...
}
}
Note the @RunWith(PowerMockRunner.class)
and @PrepareForTest(B.class)
I had to take the test using PowerMockito in separate class because adding these 2 notations made some of my other tests (which do not use PowerMockito, but only Mockito) fail.
Hope this is clear, and helps someone who is struggling with a similar problem.
Upvotes: 5