Flush a method call from another class

My code structure:

class A {
    void methodA() {
        //some code
        B b = new B();
        response = b.methodB(arg1, arg2);
        //some code using "response"
    }
}

      

I am testing a UNIT class and do not want to call the B () method. Is there a way to mock this method call with a custom response. I tried Mockito to mock this method like below:

B classBMock = Mockito.mock(B.class);
Mockito.when(classBMock.methodB(arg1, arg2)).thenReturn(customResponse);
A objA = new A();
objA.methodA();

      

When I call method A () in the above way, I don't get customResponse when methodB () is called inside A. But when I call methodB () with classBMock, I get customResponse. Anyway, I can get customResponse from methodB () when calling methodA ().

+3


source to share


1 answer


One common way to do this is to retrieve the instantiated co-author of the method and the spy

class you want to test.

In this case, you can rewrite A

as follows:

public class A {
    public B createB() {
        return new B();
    }

    public void methodA() {
        //some code
        B b = createB();
        response = b.methodB(arg1, arg2);
       //some code using "response"
    }
}

      

Now your test can spy

instantiate A

you are testing and mock for B

:



B classBMock = Mockito.mock(B.class);
Mockito.when(classBMock.methodB(arg1, arg2)).thenReturn(customResponse);
A objA = Mockito.spy(new A());
Mockito.when(objA.createB()).thenReturn(classBMock());
objA.methodA();

      


Edit:
If you can't change A

, another way might be to use PowerMock . Please note that this code snippet only shows the relevant mockery and does not display the annotations required for PowerMock to be able to manipulate your class:

B classBMock = Mockito.mock(B.class);
Mockito.when(classBMock.methodB(arg1, arg2)).thenReturn(customResponse);
PowerMockito.whenNew(B.class).withNoArguments().thenReturn(classBMock);
A objA = new A();
objA.methodA();

      

+2


source







All Articles