我想使用一个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] ...即使更改测试顺序,我也会得到相同的异常。我还试着重复第一个测试两次(相同的调用),第二个测试再次失败。我还试着用before{}和after{}启动和停止before{},但是我得到了相同的结果。我使用的是play 2.4。
有人知道我怎么修改我的代码吗?
发布于 2016-02-09 09:55:30
通过使用beforeAll和afterAll成功地修复了这个问题。
class TestSpec extends WordSpec with BeforeAndAfterAll {
override def beforeAll {
Play.start(fakeApp)
}
...
override def afterAll {
Play.stop(fakeApp)
}
}发布于 2016-02-09 10:18:57
来自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)
}
}
}
}https://stackoverflow.com/questions/35089080
复制相似问题