如何在Play中测试即发即弃的WSClient请求

时间:2016-08-04 00:56:07

标签: scala playframework playframework-2.5

基本的应用程序架构 App architecture 查看Official 2.5 WS Test Documentation,它只讨论获得同步的响应。

object GitHubClientSpec extends Specification with NoTimeConversions {

  "GitHubClient" should {
    "get all repositories" in {

      Server.withRouter() {
        case GET(p"/repositories") => Action {
          Results.Ok(Json.arr(Json.obj("full_name" -> "octocat/Hello-World")))
        }
      } { implicit port =>
        WsTestClient.withClient { client =>
          val result = Await.result(
            new GitHubClient(client, "").repositories(), 10.seconds)
          result must_== Seq("octocat/Hello-World")
        }
      }
    }
  }
}

如果我想在我的架构中测试 4,5和6 步骤,会发生什么?我可以使用WSTestClient吗?文档似乎很少见

这是我尝试测试的相关代码

def createGraphvizDotStringAndReturnImgurLink = Action.async{ implicit request =>
    import SlashCommandIn._

    slackForm.bindFromRequest.fold(
        formWithErrors => {
            Logger.warn(s"Incorrect Form Format: ${request.body.asText.getOrElse("<No Body>")}}")
            Future{Ok(Json.toJson(SlackPrivateUserResponse(BAD_FORM_DATA_MSG)))}
        },

        goodValidatedSlackRequest => {
            if(goodValidatedSlackRequest.token.contentEquals(SLACK_EXPECTED_TOKEN)) {
                Logger.debug("Validation Succeeded")
                _doImageCreationAndGetImgurLink(goodValidatedSlackRequest) // Steps, 4, 5, and 6
                Future{Ok(Json.toJson(SlackPrivateUserResponse(PROCESSING_MSG + "\n>>>" +
                  goodValidatedSlackRequest.text)))}

            }else {
                Future{Ok(Json.toJson(SlackPrivateUserResponse(BAD_TOKEN_MSG)))}
            }
        }
    )
}

1 个答案:

答案 0 :(得分:0)

通过重新构建我的架构来解决这个问题。

真的,我试图将单元测试方法与集成测试结合使用。

如果你想测试一个需要WSClient的控制器,你应该进行单元测试并在实例化控制器时注入它。

基本上,在尝试进行黑盒测试时,您无法进行白盒测试。

请参阅ScalaTest和测试控制器

上的Play文档
import scala.concurrent.Future

import org.scalatestplus.play._

import play.api.mvc._
import play.api.test._
import play.api.test.Helpers._

class ExampleControllerSpec extends PlaySpec with Results {

  "Example Page#index" should {
    "should be valid" in {
      val controller = new ExampleController()
      val result: Future[Result] = controller.index().apply(FakeRequest())
      val bodyText: String = contentAsString(result)
      bodyText mustBe "ok"
    }
  }
}

来源:https://www.playframework.com/documentation/2.5.x/ScalaTestingWithScalaTest