Scala Play 2.4 how to test action composition (using action builder and action filter)

I wrote an action constructor and applied this new action to my controller with Injection.

Below is my code:

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.......
    }
}

Without using custom actions, I can easily test UserController with ScalaTest and Mockito (Fake request and mock xxxService)

My question is, how can I make fun of AuthAction and test UserController with ScalaTest and Mockito?

thanks

+4
source share
1 answer
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)) */    
  }
}
0
source

Source: https://habr.com/ru/post/1614209/


All Articles