我正在使用Play Framework 2.3实现的Rest API。我有一些端点使用Akka actor来产生结果,我可以不幸地因为这个错误而对它们进行单元测试。另一端测试很好。要运行测试,我使用了一个伪应用程序对象,如:
@BeforeClass
public static void initResources(){
Helpers.start(getFakeApplicationInstance());
}
@AfterClass
public static void cleanupResources(){
Helpers.stop(getFakeApplicationInstance());
}
public static FakeApplication getFakeApplicationInstance() {
if(fakeApp == null)
fakeApp = Helpers.fakeApplication(TestUtil.testSettings(), new GlobalCommon());
return fakeApp;
}
@Test
public void test() {
running(testServer(3333, getFakeApplicationInstance()), () -> {
// test go here
}));
}
我不确定fakeApplication如何与akkaSystem一起工作,但似乎缺少一些东西。这是堆栈跟踪:
Test rest.RestItemTest.marshalRoomDetails failed: java.lang.IllegalStateException: Can't get ClosableLazy value after it has been closed, took 7.732 sec
[error] at play.core.ClosableLazy.get(ClosableLazy.scala:49)
[error] at play.api.libs.concurrent.AkkaPlugin.applicationSystem(Akka.scala:71)
[error] at play.api.libs.concurrent.Akka$$anonfun$system$1.apply(Akka.scala:29)
[error] at play.api.libs.concurrent.Akka$$anonfun$system$1.apply(Akka.scala:29)
[error] at scala.Option.map(Option.scala:146)
[error] at play.api.libs.concurrent.Akka$.system(Akka.scala:29)
[error] at play.api.libs.concurrent.Akka.system(Akka.scala)
[error] at play.libs.Akka.system(Akka.java:25)
[error] at utils.GlobalCommonTest.onStart(GlobalCommonTest.java:186)
[error] at utils.APIGlobalTest.onStart(APIGlobalTest.java:16)
[error] at play.core.j.JavaGlobalSettingsAdapter.onStart(JavaGlobalSettingsAdapter.scala:22)
[error] at play.api.GlobalPlugin.onStart(GlobalSettings.scala:220)
[error] at play.api.Play$$anonfun$start$1$$anonfun$apply$mcV$sp$1.apply(Play.scala:91)
[error] at play.api.Play$$anonfun$start$1$$anonfun$apply$mcV$sp$1.apply(Play.scala:91)
[error] at scala.collection.immutable.List.foreach(List.scala:381)
[error] at play.api.Play$$anonfun$start$1.apply$mcV$sp(Play.scala:91)
[error] at play.api.Play$$anonfun$start$1.apply(Play.scala:91)
[error] at play.api.Play$$anonfun$start$1.apply(Play.scala:91)
[error] at play.utils.Threads$.withContextClassLoader(Threads.scala:21)
[error] at play.api.Play$.start(Play.scala:90)
[error] at play.api.Play.start(Play.scala)
[error] at play.test.Helpers.start(Helpers.java:470)
[error] at play.test.Helpers.running(Helpers.java:486)
当我调用使用Actors的端点时,我才会这样做。任何帮助或经验分享,将不胜感激。
答案 0 :(得分:0)
这主要是由于在多个测试中重用相同的应用程序实例。在一个测试中使用应用程序上下文时,它会启动插件并启动上下文。在测试结束时,应用程序将关闭,这也会关闭插件。如果您尝试重新启动此相同的应用程序实例,则不会重新启动插件,因为它们是ClosableLazy对象,只能关闭一次。解决方案是不使用singelton模式并为每个单独的测试创建一个新的应用程序实例。所以:
public static FakeApplication getFakeApplicationInstance() {
if(fakeApp == null)
fakeApp = Helpers.fakeApplication(TestUtil.testSettings(), new GlobalCommon());
return fakeApp;
}
解决方案是:
public static FakeApplication getFakeApplicationInstance() {
return Helpers.fakeApplication(TestUtil.testSettings(), new GlobalCommon());
}
我希望这会对某人有所帮助。