处理Future [WSResponse]以查找成功或错误状态

时间:2016-04-22 17:43:52

标签: scala playframework

在Scala中,我在控制器中调用了一个服务器,它返回给我Future[WSResponse]。我想确保服务返回有效结果,因此发送Ok(..)否则发送BadRequest(...)。我认为我不能使用map。还有其他建议吗?

def someWork = Action.async(parse.xml) { request =>
  val result:Future[WSResponse] =  someService.processData(request.body.toString())
  //Need to send back Ok or BadRequest Message 
}

修改 来自@alextsc的解决方案工作正常。现在开始测试我现有的测试失败了。这是400而不是200。

test("should post something") {
  val requestBody = <value>{UUID.randomUUID}</value>
  val mockResponse = mock[WSResponse]
  val expectedResponse: Future[WSResponse] = Future.successful(mockResponse)
  val request = FakeRequest(Helpers.POST, "/posthere").withXmlBody(requestBody)

  when(mockResponse.body).thenReturn("SOME_RESPONSE")
  when(someService.processData(any[String])).thenReturn(expectedResponse)

  val response: Future[Result] = call(controller.someWork , request)

  whenReady(response) { response =>
    assert(response.header.status == 200)
  }
}

1 个答案:

答案 0 :(得分:1)

你走在正确的轨道上,是的,你可以使用map

由于您已经使用了Action.async,并且您的服务返回了未来,因此您需要做的就是将未来映射到Future [Result],以便Play可以处理它:

def someWork = Action.async(parse.xml) { request =>
  someService.processData(request.body.toString()).map {
    // Assuming status 200 (OK) is a valid result for you.
    case resp : WSResponse if resp.getStatus == 200 => Ok(...)
    case _ => BadRequest(...)
  }
}

(我注意到你的服务返回WSResponse(来自play ws java library)而不是play.api.libs.ws.Response(它的scala版本),因此getStatus而不仅仅是status #include <stdlib.h> #include <stdio.h> char statsA[100]; char fileA[50]; int main (void) { printf("Enter file to open\n"); gets(fileA); FILE *statsA; statsA = fopen("c:/Users/SeanA/C/***<fileA>***", "r+"); .......................................^ What goes here?