How to mock classes with constructor injection

ir2pid :

How to get constructor injection in Mockito

I have the following class:

class A{

  private B mB;

  A(B b){
     mB = b;
  }

 void String someMethod(){
     mB.execute();
  }
}

how do I test someMethod using a mock class A and class B using

B b = Mockito.mock(B.class)
Mockito.when(b.execute().thenReturn("String")

A a = Mockito.mock(A.class)
//somehow inject b into A and make the below statement run
Mockito.when(a.someMethod()).check(equals("String"))
rastaman :

You want to test someMethod() of class A. Testing the execute() of class B should take place in the other test, because instance of B is a dependency in your case. Test for execute() should be made in different test.

You don't need to test how B object will behave, so you need to mock it and afterwards, check that execute() was invoked.

So in your case your test will look something like this:

  B b = Mockito.mock(B.class);
  A a = new A( b );
  a.someMethod();
  Mockito.verify( b, Mockito.times( 1 ) ).execute();

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=473616&siteId=1