在我的单元测试中,我们找到了
this.mockMvc
.perform(post("/authenticate")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("username", "user@example.com")
.param("password", "superSecretPassword"))
.andExpect(status().isOk())
.andDo(document("preprocessed-request",
preprocessRequest(replacePattern(Pattern.compile("superSecretPassword"), "XXX"))));
比照Spring REST Docs documentation
这会生成内容
的build/generated-snippets/preprocessed-request/http-request.adoc
[source,http]
----
POST /authenticate HTTP/1.1
Content-Type: application/x-www-form-urlencoded
username=user%40example.com&password=superSecretPassword
----
但由于replacePattern():
,我希望屏蔽密码[source,http]
----
POST /authenticate HTTP/1.1
Content-Type: application/x-www-form-urlencoded
username=user%40example.com&password=XXX
----
我该怎么办?
答案 0 :(得分:3)
由于MockMvc处理请求参数的不幸副作用,模式替换无效。 replacePattern
对内容(即请求的正文)起作用,但MockMvc实际上并未在表单中包含表单编码的参数。
Spring REST Docs足够智能,可以在生成片段时处理此问题,例如:对于表单URL编码POST
请求,它会查看参数以确定请求的正文应该是什么。在应用replacePattern
时,它不会应用这些相同的智能。
您仍然可以使用自己的更改参数映射的OperationPreprocessor
来屏蔽密码。例如:
private OperationPreprocessor maskPassword() {
return new PasswordMaskingPreprocessor();
}
private static class PasswordMaskingPreprocessor implements OperationPreprocessor {
@Override
public OperationRequest preprocess(OperationRequest request) {
Parameters parameters = new Parameters();
parameters.putAll(request.getParameters());
parameters.set("password", "XXX");
return new OperationRequestFactory().create(request.getUri(),
request.getMethod(), request.getContent(), request.getHeaders(),
parameters, request.getParts());
}
@Override
public OperationResponse preprocess(OperationResponse response) {
return response;
}
}
然后,您可以使用此新预处理器代替replacePattern
:
this.mockMvc
.perform(post("/authenticate")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("username", "user@example.com")
.param("password", "superSecretPassword"))
.andExpect(status().isOk())
.andDo(document("preprocessed-request",
preprocessRequest(maskPassword())));