播放:控制器 class 方法的单元测试 w/ 注入
Play: Unit test for controller class method w/ injections
我正在尝试为包含注入依赖项
的控制器class的方法编写测试
这是我的测试class实现:
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
问题:如何确保我正在测试的控制器能够进行注入?
我的建议是从 WithApplication 派生测试 class 而不是手动处理应用程序生命周期。这看起来像这样
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 更多例子。
我正在尝试为包含注入依赖项
的控制器class的方法编写测试这是我的测试class实现:
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
问题:如何确保我正在测试的控制器能够进行注入?
我的建议是从 WithApplication 派生测试 class 而不是手动处理应用程序生命周期。这看起来像这样
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 更多例子。