Scala org.specs2测试中的MockServer

Scala org.specs2测试中的MockServer,scala,playframework,playframework-2.2,specs2,mockserver,Scala,Playframework,Playframework 2.2,Specs2,Mockserver,我使用PlayFramework2.2.6Scala 我想为我的应用程序编写集成测试。但是我的应用程序通过http请求一些服务,我想用它来模拟。但我不知道何时启动和停止mockServer,因为测试使用未来 @RunWith(classOf[JUnitRunner]) class AppTest extends Specification with Around { def around[T](t: => T)(implicit e: AsResult[T]): Result =

我使用PlayFramework2.2.6Scala

我想为我的应用程序编写集成测试。但是我的应用程序通过http请求一些服务,我想用它来模拟。但我不知道何时启动和停止mockServer,因为测试使用未来

@RunWith(classOf[JUnitRunner])
class AppTest extends Specification with Around {

    def around[T](t: => T)(implicit e: AsResult[T]): Result = {

        val port = 9001

        val server = new MockServer()

        server.start(port, null)

        val mockServerClient = new MockServerClient("127.0.0.1", port)

        // mockServerClient rules

        val result = AsResult.effectively(t)

        server.stop()

        result
    }

    "Some test" should {

        "some case" in new WithApplication {

            val request: Future[SimpleResult] = route(...).get

            status(request) must equalTo(OK)

            contentAsString(request) must contain(...)
        }

        "some other case" in new WithApplication {
            //
        }
    }
}

有了这段代码,我就有了java.net.ConnectException:connectionseeded:/127.0.0.1:9001。如果没有服务器,我就无法执行此操作。停止,因为服务器必须在不同的测试中运行。

我找到了解决方案,我查找了WithApplication的源代码(它扩展了)并使用MockServer编写了抽象类:

abstract class WithMockServer extends WithApplication {

  override def around[T: AsResult](t: => T): Result = {

    Helpers.running(app) {

      val port = Play.application.configuration.getInt("service.port").getOrElse(9001)
      val server = new MockServer(port)

      val mockServerClient = new MockServerClient("127.0.0.1", port)

      // mockServer rules

      val result = AsResult.effectively(t)
      server.stop()
      result
    }
  }
}

在每一个测试用例中,我都将newwithapplication中的
替换为newwithmockserver中的

,您可以尝试使用
aroundach
特性吗?这是您希望围绕每个示例执行行为时要使用的特性。然后,如果您想检查未来,通常可以使用
contain(…).wait
,前提是在作用域中有一个隐式
ExecutionEnv
:类AppTest(隐式ee:ExecutionEnv)使用AroundEach扩展规范。如果这对你合适的话,我会把它变成一个答案。