A mocking addiction that is not visible from the outside

I have unit test some old code that was not designed to support unit testing (No DI). Is there a way to mock an object that is initialized in a public method?

public int method() { A a = new A(ar1, arg2); //How to mock this? } 

Thanks,

-Abidi

+4
source share
2 answers

Another option is to reorganize 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, you can now use the Mockito spy and doAnswer to override createA on your test device with something like strings:

 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()); 
+1
source

If you have control over the code in question, you can reorganize it and make the dependency dependent, for example, depending on some A-builder. This is probably the best solution, as it makes your class less dependent on A [Forcing the decoupling of your design is one of the main benefits of testing.]

0
source

All Articles