org.specs2 测试中的 MockServer

MockServer in org.specs2 tests

我使用 playframework 2.2.6 scala。

我想为我的应用程序编写集成测试。但是我的应用程序通过 http 请求一些服务,我想用 mockServer 模拟它。但是我不知道什么时候开始和停止 mockServer 因为测试使用 futures

@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:连接被拒绝:/127.0.0.1:9001。如果没有 server.stop 我无法做到这一点,因为服务器在不同的测试中必须是 运行。

我找到了解决方案,我查看了 WithApplication 的源代码(它扩展了 Around)并写了摘要 class WithMockServer:

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
    }
  }
}

并且在每个测试用例中,我将 in new WithApplication 替换为 in new WithMockServer