我编写了一个动作构建器,并使用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?
由于
答案 0 :(得分:0)
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)) */
}
}