0

I'm new to Mockito and unit testing in general, so here's a basic question. Given this class:

public class A{
  private B b;

  public A(){
    b = new B();
  }

  private void test(){
    b.some_other_method();
  }
}

Won't this successfully stub down the chain?

a = Mockito.mock(A.class);
b = Mockito.mock(B.class);

Mockito.when(b.some_other_method()).thenReturn("testing");
a.test();

Thanks!

mstrom
  • 1,655
  • 3
  • 26
  • 41

1 Answers1

2

This won't work as you have it, because the b in your test is a different instance than the b in your A class.

Also bear in mind that you shouldn't be mocking your class under test. I wrote a summary in another answer, but suffice to say that you should use a real A and a mock B in a test that's supposed to test A.

You can insert your replacement B instance this way, for instance:

public class A{
  private B b;

  public A(){
    b = new B();
  }

  /** Package private constructor used for testing. */
  A(B b){
    this.b = b;
  }

  private void test(){
    b.some_other_method();
  }
}

At this point you just call new A(b) in your test, referring to your mocked B instance.

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251