scala - 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
.
解决方案
推荐阅读
- python - Python3,从txt文件中逐行读取并将行拆分为两个变量
- swift - 为什么 InAppSettingsKit 会覆盖我的 TabBarItemTitle?
- react-native - React Navigation 4x 内存泄漏
- python - python中的Discord bot,检查命令是否为空
- python - 需要帮助对每个条目中包含字母和数字的列表进行排序
- ssas - 如何在一个 JSON 块中清除然后刷新数据库?
- alert - 如何从 Prometheus 获得上周的“UP”指标计数 = 0?
- swiftui - 在“更多”溢出中显示来自选项卡的警报让我回到上一个视图
- azure-api-management - 如何将 OpenAPI 架构定义包含到 ARM 模板中
- node.js - jwt刷新后req.user丢失数据