The B
instance will be constructed before being spied, so the reference that C
receives is the actual B
object and not the spied instance.
You're adding behaviour to the spied instance which is indeed a different object to the one that C.bObject
has, so the behaviour is not applied. Similarly setting b.otherValue
will not result on b.cObject.bObject.otherValue
being set.
You can see that these are different objects - assuming a default toString
is present:
final B b = Mockito.spy(new B());
System.out.println("spied: " + b);
System.out.println("b.cObject.bObject: " + b.cObject.bObject);
It should produce something along the lines of:
spied: B$$EnhancerByMockitoWithCGLIB$$999ce15d@7a187814
b.cObject.bObject: B@5c73a7ab
Perhaps you could use reflection to set b.cObject.bObject
field to the spied instance? For example:
final Field f = C.class.getDeclaredField("bObject");
f.setAccessible(true);
f.set(b.cObject, b);