首页 > 解决方案 > akka http mock(授权)指令

问题描述

我正在尝试将单元测试写入 akka-http 服务器(路由),但在授权指令方面遇到了问题。我只是想忽略(模拟)授权指令。

我的代码的最小版本:

object App {

    val logger: Logger = Logger[App]

    def main(args: Array[String]): Unit = {
        implicit val system: ActorSystem = ActorSystem("my-system")
        implicit val executionContext: ExecutionContextExecutor = system.dispatcher

        val service = new TestRoute()
        val bindingFuture = Http().bindAndHandle(service.route, "0.0.0.0", 8080)

        bindingFuture.onComplete {
            case Success(_) => println(s"listening on localhost:8080")
            case Failure(error) => println(s"failed: ${error.getMessage}")
        }
    }


    object TestRoute {

        def authorize: Directive1[JsObject] = extractCredentials.flatMap {
            case Some(OAuth2BearerToken(token)) => verifyToken(token) match {
                case Success(t) =>
                    logger.debug("token verified successfully")
                    provide(t)
                case Failure(t) =>
                    logger.warn(s"token is not valid: ${t.getMessage}")
                    reject(Rejections.validationRejection(t.getMessage))
            }
            case _ =>
                logger.warn("no token present in request")
                reject(AuthorizationFailedRejection)
        }


        def verifyToken(token: String): Try[JsObject] = {
            val source = Source.fromResource("public_production.pem")
            val fileData = try source.mkString finally source.close()
            JwtSprayJson.decodeJson(token, fileData, Seq(JwtAlgorithm.RS256))
        }
    }

    class TestRoute {
        val route: Route =
            TestRoute.authorize { jwtClaims =>
                println(jwtClaims)
                complete("sucess")
            } 
    }
}

我想在TestRoute. authorize我想模拟的指令也是如此。我只是想控制authorize将返回的内容,而不必实际进入函数。

我的同事建议将 Route 包装在某种类中,该类将authorize方法作为参数,这样在单元测试中我可以很容易地控制它。但我正在寻找模拟答案。

我看到了一些使用 Mockito 的示例,但没有一个与我的最新版本兼容,即3.1.0.

标签: scalaunit-testingmockingakkaakka-http

解决方案


推荐阅读