Prateek Chachra Prateek Chachra - 1 month ago 9
Java Question

How To Use @InjectMocks For A Dependency For Another Class To Be Mocked?

Say I have a class :

public class Boy
{
@Inject
@Named("birthDay")
BirthDay bday;
}


And I want to mock it, but the problem is the BirthDay class itself uses a dependency which I want to mock and control as well, I cannot use both @InjectMocks and @Mock on the same class, how do you go about achieving the same?

Answer

Why do you need to inject something in the mock? You need to have two test classes for testing Boy and BirthDay classes.

Here you sould test logic of a Boy class

public class BoyTest{
  @Mock
  private BirthDay brithday;

  @InjectMock
  private Boy boy;
}

And logic of a BirthDay should have it's own Test class.

public class BirthDayTest {
  @Mock
  private Dependency dependency ;

  @InjectMock
  private BirthDay brithday;
}

So, you should assume that your mock returns some data that you need. And check that your Unit under test works as expected with given data.

Comments