在 Play 中使用 ScalaTest 对控制器进行单元测试!框架

Unit testing controllers with ScalaTest in Play! framework

我正在使用 Play 2.2 和 ScalaTest。这是我第一次尝试在我的播放应用程序中测试控制器。我是这样做的:

class TestArtistController extends PlaySpec with OneAppPerSuite {

  "ArtistController" must {

    "returns artists" in new WithApplication {
      val eventuallyResult = controllers.ArtistController.findNearCity("lyon")(FakeRequest())
      whenReady(eventuallyResult, timeout(Span(2, Seconds))) { result =>
        println(result.body) //it is an Enumerator[Array[Byte]]
        result.header.status mustBe 200
      }
    }
  }
}

它允许我正确地测试 return 结果,但我不知道如何测试结果的主体。 result.body return 一个 Enumerator[Array[bytes]] 我完全不知道如何转换它来检索我发送的 Json

这样做的好方法是什么?

导入 play.api.test.Helpers._ 并使用 contentAsJson(res)status(res) 等辅助函数,其中 res 是您操作的结果(您可能需要使用 res.run 在某些情况下用于异步操作)。