You would need to use a factory pattern and inject a mocked factory into the class where the instances are being created.
So, if you want to write tests for some class Foo
, which needs to create instances of Bar
somewhere in its code, you would need to inject a BarFactory
into Foo
. Injection can happen the old fashioned way by passing a BarFactory
into the constructor or a set method, or with a dependency injection framework like Guice. A brief example of the old-fashioned way:
class Foo {
private final BarFactory mFactory;
public Foo(BarFactory factory) {
mFactory = factory;
}
public void someMethodThatNeedsABar() {
Bar bar = mFactory.create();
}
}
Now, in your test class you can inject a mocked BarFactory
that can produce mocked instances of Bar
:
Bar mockBar = mock(Bar.class);
BarFactory mockFactory = mock(BarFactory.class);
when(mockFactory.create()).thenReturn(mockBar);
Foo objectForTest = new Foo(mockFactory);