This is the class structure:
class A {
private B b;
A() {
b = new B();
}
public void foo() {
b.anotherMethod();
}
}
Test class:
class TestA {
@Mock
B b;
@Test
public testFoo() {
A a = new A();
when(b.anotherMethod()).thenReturn("something");
a.foo();
}
}
I want to mock object of b, but it's never getting mocked. new B() creates an object of B and real anotherMethod() gets called instead of the thenReturn("something") How can I mock new B() to return mocked object of B so that anotherMethod() doesn't get called?