samedi 9 juillet 2016

Mocking method for all instances of class with PowerMockito

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(){}
}
public class A{
    public void veryImportantMethod(){
        B newB = new B();
        newB.veryAnnoyingMethod();
        ...
    }
}

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());

But it throws exception, and I don't think it is what I actually need.

Aucun commentaire:

Enregistrer un commentaire