在我的jersey-2应用程序中,我使用了一个非常简单的ContainerRequestFilter,它将检查基本身份验证(可能会重新发明轮子,但请耐心等待)。筛选器的工作原理如下
@Override
public void filter(ContainerRequestContext context) throws IOException {
String authHeader = context.getHeaderString(HttpHeaders.AUTHORIZATION);
if (StringUtils.isBlank(authHeader)) {
log.info("Auth header is missing.");
context.abortWith(Response.status(Response.Status.UNAUTHORIZED)
.type(MediaType.APPLICATION_JSON)
.entity(ErrorResponse.authenticationRequired())
.build());
}
}现在,我想为它编写一个测试,模拟ContainerRequestContext对象。
@Test
public void emptyHeader() throws Exception {
when(context.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn(null);
filter.filter(context);
Response r = Response.status(Response.Status.UNAUTHORIZED)
.type(MediaType.APPLICATION_JSON)
.entity(ErrorResponse.authenticationRequired())
.build();
verify(context).abortWith(eq(r));
}此测试在eq(r)调用上失败,即使查看Response对象的字符串表示形式它们是相同的。知道出什么问题了吗?
发布于 2017-09-15 10:10:23
我不相信你需要eq()方法。您应该验证该上下文。调用了abortWith(r)。但是,我可能遗漏了一些东西,因为您没有包括eq(r)是什么。
发布于 2021-10-22 07:01:09
因为我有同样的问题,所以我是这样做的:
@Test
public void abort() {
new MyFilter().filter(requestContext);
ArgumentCaptor<Response> responseCaptor = ArgumentCaptor.forClass(Response.class);
verify(requestContext).abortWith(responseCaptor.capture());
Response response = responseCaptor.getValue();
assertNotNull(response);
JerseyResponseAssert.assertThat(response)
.hasStatusCode(Response.Status.FORBIDDEN);
}https://stackoverflow.com/questions/26592140
复制相似问题