You can do this, see the answer by Matt Lachman. That approach isn't recommended however. It's a bit hacky.
The best approach would be to delegate creation of your dependant objects to a factory pattern and inject the factories into your A
class:
class BFactory {
public B newInstance() {
return new B();
}
}
class CFactory {
public C newInstance() {
return new C();
}
}
class A {
private final BFactory bFactory;
private final CFactory cFactory;
public A(final BFactory bFactory, final CFactory cFactory) {
this.bFactory = bFactory;
this.cFactory = cFactory;
}
public void f() {
B b = bFactory.newInstance();
C c = cFactory.newInstance();
}
}
You would then mock the factories to return mock instances of the dependent classes.
If for some reason this is not viable then your can create factory methods in the A
class
class A {
public void f() {
B b = newB();
C c = newC();
}
protected B newB() {
return new B();
}
protected C newC() {
return newC();
}
}
Then you can use a spy
that mocks those factory methods.