Abidi
Abidi

Reputation: 7996

Mocking a dependency that is not visible outside

I have to unit test some old code that wasn't designed to support unit testing (No DI). Is there a way to mock an object that is being initialized within a public method?

public int method() {

    A a = new A(ar1, arg2); //How to mock this?

}

Thanks,

-Abidi

Upvotes: 4

Views: 574

Answers (2)

Jeff Foster
Jeff Foster

Reputation: 44706

Another option is to refactor the code into

public int method() {
   A a = createA(arg1,arg2);
}

A createA(int arg1, int arg2) {
    return new A(arg1,arg2);
}

In your test method now you can use Mockito's spy and doAnswer functions to override createA on your test fixture with something along the lines of:

Foo foo = new Foo();
Foo spiedFoo = spy(foo); // a spied version when you can copy the behaviour
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock inv) throws Throwable {
        A a = mock(A.class);
        return a;
    }
}).when(mySpy).createA(anyInt(), anyInt());

Upvotes: 1

zoul
zoul

Reputation: 104065

If you have control over the code in question, you can refactor it and make the dependency public, for example by depending on some A-builder. This is probably the best solution, since it makes your class less dependent on A. [Forcing you to decouple your design is one of the main advantages of testing.]

Upvotes: 0

Related Questions