【问题标题】:MockServer in org.specs2 testsorg.specs2 测试中的 MockServer
【发布时间】:2017-06-18 06:48:43
【问题描述】:

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

【问题讨论】:

  • 您可以尝试使用AroundEach 特征吗?当您想围绕每个示例执行行为时,这是要使用的特征。然后如果你想检查期货,你通常可以使用contain(...).await,前提是你在范围内有一个隐含的ExecutionEnvclass AppTest(implicit ee: ExecutionEnv) extends Specification with AroundEach。如果它适合你,我会把它变成一个答案。

标签: scala playframework playframework-2.2 specs2 mockserver


【解决方案1】:

我找到了解决方案,我查看了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 WithApplication 替换为in new WithMockServer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 2019-09-08
    • 2016-04-24
    • 2021-04-25
    • 2023-04-05
    • 2021-08-27
    • 1970-01-01
    相关资源
    最近更新 更多