FakeRequest 向下转换为 RequestHeader

Posted

技术标签:

【中文标题】FakeRequest 向下转换为 RequestHeader【英文标题】:FakeRequest down-casted to RequestHeader 【发布时间】:2016-11-25 16:23:50 【问题描述】:

我有一个受 Authentication trait 保护的控制器。特征如下所示:

def isAuthenticated(f: => AccountDTO => Request[AnyContent] => Result) =
    Security.Authenticated(username, onUnauthorized)  user =>
      Action.async 
        request => 
          Future.successful(f(user)(request))
        
      
    

在进行正常请求时一切正常,但在进行单元测试时遇到问题。 我创建了以下虚假请求:

val goodRequest = FakeRequest("POST", "/platform/api/v1/files")
.withBody(Json.toJson(ScalaMockingUtil.fileValidMetadataJson))
      .withHeaders((HeaderNames.AUTHORIZATION, "4322tertf2643t34t34"))

接下来,我获取我的控制器对象并通过应用该 FakeRequest 来调用该方法:

val result: Iteratee[Array[Byte], Result] = filesController.createFileMetadata()(goodRequest)

我面临的问题是,FakeReuqest 在某处被向下转换为 RequestHeader。问题似乎是这里描述的问题:Unable to test controller using Action.async 其中 Action 有两个 apply 方法而不是一个。但是,我似乎无法强制执行我需要的那个。

感谢任何帮助。

【问题讨论】:

【参考方案1】:

解决方案(或解决方法)是使用 call() 而不是 apply():

val result = call(filesController.createFileMetadata(), goodRequest)

现在一切都按预期进行。

【讨论】:

以上是关于FakeRequest 向下转换为 RequestHeader的主要内容,如果未能解决你的问题,请参考以下文章

40-向下转换 as 定义接口

将 double 转换为 Int,向下舍入

如何正确检查是不是成功向下转换为 AnyObject?

c - 整数向下转换

如何在 for in 循环中向下转换为 [String: String]?

向下转换并同时从 const 转换为 non-const