[英]How to test jersey2 request filters?
In my jersey-2 application I'm using a very simple ContainerRequestFilter
that will check for basic authentication (probably reinventing the wheel, but bear with me).在我的 jersey-2 应用程序中,我使用了一个非常简单的
ContainerRequestFilter
,它将检查基本身份验证(可能是重新发明轮子,但请耐心等待)。 Filter goes somewhat like this过滤器有点像这样
@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());
}
}
Now I'd like to write a test for it, mocking the ContainerRequestContext
object.现在我想为它编写一个测试,模拟
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));
}
This test fails on the eq(r)
call, even if looking at the string representation of the Response
objects they are the same.该测试在
eq(r)
调用中失败,即使查看Response
对象的字符串表示,它们也是相同的。 Any idea what's wrong?知道出了什么问题吗?
I don't believe you need the eq() method. 我不相信你需要eq()方法。 You should verify that context.
您应该验证该上下文。 abortWith(r) was called.
abortWith(r)被召唤。 I might be missing something though because you've not included what eq(r) is.
我可能会遗漏一些东西,因为你没有包括eq(r)是什么。
Since I had the same question, I did it like this:由于我有同样的问题,我是这样做的:
@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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.