我想使用FakeApplication测试WS调用,目前我喜欢这样:
class ExampleServiceSpec extends WordSpec with BeforeAndAfter {
private val client = new GenericGrafanaService
"Service" should {
"post some json" in {
Play.start(fakeApp)
assertResult("OK") {
Await.result(client.postSomeJson("key1", "string2"), Duration.Inf)
}
Play.stop(fakeApp)
}
"delete some json" in {
Play.start(fakeApp)
assertResult("OK") {
Await.result(client.deleteSomeJson("key1"), Duration.Inf)
}
Play.stop(fakeApp)
}
}
}
并且第一次测试通过,但是对于下一个测试,我得到一个像这样的例外:
[info] java.io.IOException: Closed
[info] at com.ning.http.client.providers.netty.request.NettyRequestSender.sendRequest(NettyRequestSender.java:96)
[info] at com.ning.http.client.providers.netty.NettyAsyncHttpProvider.execute(NettyAsyncHttpProvider.java:87)
[info] at com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:506)
[info] at play.api.libs.ws.ning.NingWSClient.executeRequest(NingWS.scala:47)
[info] at play.api.libs.ws.ning.NingWSRequest.execute(NingWS.scala:306)
[info] at play.api.libs.ws.ning.NingWSRequest.execute(NingWS.scala:128)
[info] at play.api.libs.ws.WSRequest$class.delete(WS.scala:500)
[info] at play.api.libs.ws.ning.NingWSRequest.delete(NingWS.scala:81)
[info] at de.zalando.steerage.abdiff.grafana.interface.ExampleService$$anonfun$deleteSomeJson$1.apply(ExampleService.scala:58)
[info] at de.zalando.steerage.abdiff.grafana.interface.ExampleService$$anonfun$deleteSomeJson$1.apply(ExampleService.scala:56)
[info] ...
即使我改变了测试的顺序,我也得到了相同的异常。我也试过重复第一次测试两次(同一次调用),第二次尝试再次失败。我还尝试使用fakeApp
和before{}
启动和停止after{}
,但我得到了相同的结果。我正在玩2.4。
任何人都知道如何调整我的代码?
答案 0 :(得分:1)
使用beforeAll
和afterAll
进行管理以解决此问题。
class TestSpec extends WordSpec with BeforeAndAfterAll {
override def beforeAll {
Play.start(fakeApp)
}
...
override def afterAll {
Play.stop(fakeApp)
}
}
答案 1 :(得分:0)
来自https://www.playframework.com/documentation/2.4.x/ScalaFunctionalTestingWithScalaTest
有时您想要使用真正的HTTP堆栈进行测试。如果测试类中的所有测试都可以重用相同的服务器实例,则可以混合使用OneServerPerSuite(这也将为该套件提供新的FakeApplication)
例如:
class ExampleServiceSpec extends WordSpec with BeforeAndAfter {
private val client = new GenericGrafanaService
"Service" should {
"post some json" in {
assertResult("OK") {
Await.result(client.postSomeJson("key1", "string2"), Duration.Inf)
}
}
"delete some json" in {
assertResult("OK") {
Await.result(client.deleteSomeJson("key1"), Duration.Inf)
}
}
}
}