0

我使用 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 我不能这样做,因为该服务器必须在不同的测试中运行。

4

1 回答 1

0

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

于 2017-02-06T08:51:54.353 回答