【问题标题】:Ktor: Mock PrincipalKtor:模拟校长
【发布时间】:2021-10-08 08:16:08
【问题描述】:

我有以下路线:

   get("/user") {
        val principal: UserIdPrincipal = call.principal()
            ?: return@get call.respond(HttpStatusCode.Unauthorized)
        val user = userService.findUserForId(principal.name.toLong())
            ?: return@get call.respond(HttpStatusCode.Unauthorized)

        val userResponse = UserResponse(username = user.username)
        call.respond(userResponse)
    }

我不想测试身份验证是否适用于我的每条路由,所以我想模拟call.principal()。由于它是内联扩展函数,因此不能轻易模拟。任何想法如何解决这个问题?

【问题讨论】:

    标签: ktor


    【解决方案1】:

    如果您可以在测试中更改Authentication 插件的配置,那么您可以注册一个提供程序,在AuthenticationPipeline.RequestAuthentication 阶段拦截其管道,以获取对身份验证上下文的访问权限,最后分配新的主体。这是一个例子:

    import io.ktor.application.*
    import io.ktor.auth.*
    import io.ktor.response.*
    import io.ktor.routing.*
    import io.ktor.server.engine.*
    import io.ktor.server.netty.*
    
    fun main() {
        val server = embeddedServer(Netty, port = 8080) {
            install(Authentication) {
                provider {
                    pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context ->
                        context.principal(UserIdPrincipal("principal"))
                    }
                }
            }
    
            routing {
                authenticate {
                    get("/user") {
                        val principal: UserIdPrincipal = call.principal()!!
                        call.respond(principal.name)
                    }
                }
            }
        }
    
        server.start(wait = true)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 2015-04-24
      • 1970-01-01
      • 2012-01-30
      相关资源
      最近更新 更多