游戏:控制器类方法的单元测试w / injections

时间:2016-10-04 09:42:45

标签: java unit-testing junit playframework playframework-2.5

我试图为包含注入依赖项的控制器类的方法编写测试

这是我的测试类实现:

public class MyTestClass {
   private static Application app;

   @BeforeClass
   public static void beforeTest() {
      app = Helpers.fakeApplication(Helpers.inMemoryDatabase());
      Helpers.start(app);

      // .....
   }

   @AfterClass
   public static void afterTest() {
       Helpers.stop(app);
   }

   @Test
   public void testSomething() {

       // .....
       app.injector().instanceOf(MyController.class).processSomething();

       // Some assertions here..
   }

}

MyController.processSomething()方法包含一些涉及使用注入的FormFactory对象的实现。

当我尝试跑步时,我会得到null

[error] Test MyTestClass.testSomething failed: null, took 0.137 sec
[error] Failed: Total 1, Failed 1, Errors 0, Passed 0
[error] Failed tests:
[error]         MyTestClass
[error] (test:test) sbt.TestsFailedException: Tests unsuccessful


问题:如何确保我测试的控制器能够进行注射?

1 个答案:

答案 0 :(得分:2)

我的建议是从WithApplication派生测试类,而不是手动处理应用程序生命周期。这看起来像这样

public class MyTestClass extends WithApplication {
    @Test
    public void testSomething() {
        Helpers.running(Helpers.fakeApplication(), () -> {
            // *whatever mocking*
            RequestBuilder mockActionRequest = Helpers.fakeRequest(
                                         controllers.routes.MyController.processSomething());
            Result result = Helpers.route(mockActionRequest);
            // *whatever assertions* 
       });
     }
}

您可以更多here个例子。