ALEX_AME ALEX_AME - 3 months ago 11
Java Question

How do I inject dependencies in controller tests?

This is my class and its constructor and the dependencies.

public class FavouriteProfilesController extends BaseController implements CurrentUser, JsonHelper {

private final UserProvider userProvider;
private MessagesApi msg;

@javax.inject.Inject
public FavouriteProfilesController(
UserProvider userProvider,
MessagesApi msgApi) {
this.userProvider = userProvider;
this.msg = msgApi;
}
// methods etc...


This is the test code I just copied from the docs:

public class FavouriteProfilesControllerTest extends WithApplication {

@Override
protected Application provideApplication() {
return new GuiceApplicationBuilder()
.configure("play.http.router", "javaguide.tests.Routes")
.build();
}

@Test
public void testIndex() {
Result result = new FavouriteProfilesController().index(); // Inject dependencies here
assertEquals(OK, result.status());
assertEquals("text/html", result.contentType().get());
assertEquals("utf-8", result.charset().get());
assertTrue(contentAsString(result).contains("Welcome"));
}


}


The controller has 2 dependencies, UserProvider and MessagesApi, how do I inject/mock them into the controller test?

Answer

If you use Mockito, you can mock them like this:

@RunWith(MockitoJUnitRunner.class)
public class FavouriteProfilesControllerTest extends WithApplication {

   @InjectMocks
   private FavouriteProfilesController controller;

   @Mock
   private UserProvider userProvider;

   @Mock
   private MessagesApi msg;

   @Test
   public void test() {
     Assert.assertNotNull(userProvider);
     Assert.asserNotNull(msg);
   }
}