如何在控制器测试中注入依赖项?

时间:2016-08-29 19:51:10

标签: java playframework

这是我的类及其构造函数和依赖项。

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... 

这是我刚刚从文档中复制的测试代码:

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"));
   }


}

控制器有2个依赖项,UserProvider和MessagesApi,如何将它们注入/模拟到控制器测试中?

2 个答案:

答案 0 :(得分:1)

如果您使用Mockito,您可以像这样嘲笑它们:

@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);
   }
}

答案 1 :(得分:1)

解决方案取决于您打算测试的内容。如果你想模仿UserProvider和MessageApi的整个行为,使用Mockito可能是一个合适的解决方案。 如果您想使用真实对象测试控制器功能,则需要注入真实对象。这可以这样做:

public class FavouriteProfilesControllerTest extends WithApplication {
    @Test
    public void testIndex() {
        running(Helpers.fakeApplication(), () -> {
            RequestBuilder mockActionRequest = Helpers.fakeRequest(
                controllers.routes.FavouriteProfilesController.index());
            Result result = Helpers.route(mockActionRequest);
            assertEquals(OK, result.status());
            assertEquals("text/html", result.contentType().get());
            assertEquals("utf-8", result.charset().get());
            assertTrue(contentAsString(result).contains("Welcome"));
        });
    }
}

如果您不打算在测试中使用不同的注入绑定,则无需使用GuiceApplicationBuilder。调用Helpers.fakeApplication()会调用默认的依赖注入。

您可以在Play here中找到有关单元测试的更多信息。