Another solution is to spy on the Foo object itself, allowing you to verify the interactions with the Bar object through the spy. This is less common and more of a workaround if you don’t want to modify the original code.
Test Code with Mockito Spy:
import static org.mockito.Mockito.*;
public class FooTest {
@Test
public void testFoo() {
// Spy on the Foo class (this is not a mock, it's a partial mock)
Foo spyFoo = spy(new Foo());
// Mock the Bar instance within the Foo class
Bar mockBar = mock(Bar.class);
// Replace the Bar instance inside Foo with the mock
doReturn(mockBar).when(spyFoo).createBar();
// Call the method under test
spyFoo.foo();
// Verify the method was called on the mock Bar
verify(mockBar, times(1)).someMethod();
}
}
In this example, you spy on the Foo object and override the method that creates Bar. This approach is a bit more complex and usually requires you to provide an additional method like createBar() that can be mocked.