首页 > 解决方案 > 如何测试从服务器拦截器设置的上下文键值

问题描述

我正在尝试为我的身份验证服务器拦截器编写单元测试。拦截器从附加的元数据头中提取用户 ID 信息,并将其存储为 ContextKey,稍后在服务调用中使用。我是根据这个线程的说明完成的。

基于HeaderServerInterceptorTest示例,我设置了自己的测试,它确实调用了拦截器。但是,当尝试断言用户 ID 值时,它始终为空。

我的拦截器类是:

@Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
            ServerCallHandler<ReqT, RespT> next) {

// authentication and extracting user ID info

        Context context = Context.current();
        return Contexts.interceptCall(context.withValue(USER_ID, id), call, headers, next);
    }

断言总是失败,因为 USER_ID 值为空。

assertEquals("john_doe_ID", MyServerInterceptor.getUserID());

我猜我在测试中缺少 Context 的一些额外配置,但我找不到类似的东西......

标签: javagrpc

解决方案


推荐阅读