lundi 25 janvier 2016

Inject mock bean into tested Object

How can I inject a mocked bean that has certain behaviour defined into a a class that is under test but when it's initiated the constructor calls that mock and execute certain action against it.

So for example I have this class that I would like to test:

public class A {

   @Autowired 
   private B b;

   private String result = null;

   public A(int c) {
      result = b.calculateStuff(c) + "AA";
   } 

   public String getResult() {
      return result + "A";
   }
}

Now the test class:


public class ATest{

   @Mock
   private B b;

   @InjectMocks
   private A a;

   @Before
   public void setUp() {
      doReturn("String result!").when(B).get(anyInt());
      MockitoAnnotations.initMocks(this);
   }

   public void testGetResult() {
      assertEquals(a.getResult(),"String result!AAA");
   }
}

How can I actually inject a mock into A ? Is there a better way of approaching this?

Aucun commentaire:

Enregistrer un commentaire