加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala Play 2.4如何测试动作组合(使用动作构建器和动作过滤器)

发布时间:2020-12-16 19:23:16 所属栏目:安全 来源:网络整理
导读:我编写了一个动作构建器,并使用Injection将此新动作应用于我的控制器. 以下是我的代码: class AuthAction @Inject()(authService: AuthService) { def AuthAction(userId: Int) = new ActionBuilder[Request] with ActionFilter[Request] { def filter[A](r
我编写了一个动作构建器,并使用Injection将此新动作应用于我的控制器.

以下是我的代码:

class AuthAction @Inject()(authService: AuthService) {
    def AuthAction(userId: Int) = new ActionBuilder[Request] with ActionFilter[Request] {
        def filter[A](request: Request[A]): Future[Option[Result]] = {
            request.headers.get("Authorization").map(header => {
                authService.isAuth(header).flatMap {
                    case true => Future.successfuly(None)
                    case false => Future.successfuly(Some(Forbidden))
                }
            })
        }
    }
}

class UserController @Inject()(auth: AuthAction,xxxService: XxxService) extends Controller {
    def xxx(userId: Int) = auth.AuthAction(userId).async { implicit request =>
        xxxService.xxx().map.......
    }
}

不使用自定义操作,我可以使用ScalaTest和Mockito轻松测试UserController(假请求和模拟xxxService)

我的问题是如何使用ScalaTest和Mockito模拟AuthAction并测试UserController?

谢谢

解决方法

val authAction = mock[AuthAction]

when(authAction.AuthAction(any[Int])).thenReturn {
  new ActionBuilder[Request] with ActionFilter[Request] {
    def filter[A](request: Request[A]): Future[Option[Result]] = 
      Future.successful(None) /* or Future.successful(Some(Forbidden)) */    
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读