org.specs2测试中的MockServer

时间:2017-02-01 13:37:46

标签: scala playframework playframework-2.2 specs2 mockserver

我使用playframework 2.2.6 scala。

我想为我的应用程序编写集成测试。但我的应用程序通过http请求一些服务,我想用mockServer来模拟它。但我不知道何时开始和停止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:连接被拒绝:/127.0.0.1:9001。如果没有server.stop,我就无法在不同的测试中运行服务器。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,我查看了WithApplication的源代码(它扩展了)并编写了抽象类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