首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在控制器测试中注入依赖项?

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

Stack Overflow用户
提问于 2016-08-29 19:51:10
回答 2查看 110关注 0票数 1

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

代码语言:javascript
复制
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... 

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

代码语言:javascript
复制
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"));
   }


}

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-29 20:05:55

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

代码语言:javascript
复制
@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
EN

Stack Overflow用户

发布于 2016-08-30 11:33:25

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

代码语言:javascript
复制
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 这里中找到更多关于单元测试的信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39214096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档