我正在做一个项目,我需要写一个拦截器,它基本上是修改头。
class AuthRequestInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "auth-value");
Request request = requestBuilder.build();
return chain.proceed(request);
}
}
我想测试拦截器是否将Authorization添加到了请求头中。
class AuthRequestInterceptorTest extends Specification {
AuthRequestInterceptor authRequestInterceptor = new AuthRequestInterceptor();
OkHttpClient okHttpClient = new OkHttpClient();
void setup() {
try {
okHttpClient = new OkHttpClient()
.newBuilder()
.addInterceptor(authRequestInterceptor)
.build();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new WebClientException(e)
}
}
def "Get Authorization in to header"() {
given:
HashMap<String, String> headers = new HashMap<>()
when:
Request mockRequest = new Request.Builder()
.url("http://1.1.1.1/heath-check")
.headers(Headers.of(headers))
.build()
Response res = okHttpClient.newCall(mockRequest).execute()
then:
res.headers("Authorization")
}
}
测试失败,因此我调试了AuthRequestInterceptor返回的响应,如下所示
Response{protocol=h2, code=200, message=, url=https://1.1.1.1/}
我想测试请求标头中是否添加了授权密钥,但我只能获取响应,无法确定如何获取请求标头
1条答案
按热度按时间efzxgjgh1#
帮助程序类:
测试中的类别:
斯波克规格:
为了隔离地测试拦截器,只需模拟拦截器链参数,确保它返回一个没有头的请求,然后验证
proceed(Request)
方法是用一个包含所需头的请求参数调用的。请在Groovy Web Console中尝试。
您可能想了解Spock论证约束。