泽西极有可能编写与泽西一起编写的REST-API集成测试。 只需扩展类JerseyTest并继续就可以了。
我遇到一个问题,我不得不模拟SecurityContext ,以便SecurityContext包含一个特殊的UserPrincipal 。 挑战在于Jersey在测试中将SecurityContext包装在自己的类SecurityContextInjectee中。 因此,我必须将SecurityContext Mock添加到此Jersey的包装器类中。 让我在一个示例中进行演示。
假设我有以下泽西岛资源:
@Path("hello/world")
public class MyJerseyResource {
@GET
public Response helloWorld(@Context final SecurityContext context) {
String name = context.getUserPrincipal().getName();
return Response.ok("Hello " + name, MediaType.TEXT_PLAIN).build();
}
}
在我的测试中,我必须模拟SecurityContext ,以便可以在测试期间使用预定义的用户主体。 我使用Mockito作为模拟框架。 我的模拟如下
final SecurityContext securityContextMock = mock(SecurityContext.class);
when(securityContextMock.getUserPrincipal()).thenReturn(new Principal() {
@Override
public String getName() {
return "Alice";
}
});
为了将此模拟的SecurityContext添加到包装类SecurityContextInjectee中 ,我必须在Jersey测试中配置带有修改后的ContainerRequestContext的ResourceConfig 。 可以在此修改后的ContainerRequestContext中设置模拟的SecurityContext ,然后在包装器类中使用它:
@Override
public Application configure() {
final SecurityContext securityContextMock = mock(SecurityContext.class);
when(securityContextMock.getUserPrincipal()).thenReturn(new Principal() {
@Override
public String getName() {
return "Alice";
}
});
ResourceConfig config = new ResourceConfig();
config.register(new ContainerRequestFilter(){
@Override
public void filter(final ContainerRequestContext containerRequestContext) throws IOException {
containerRequestContext.setSecurityContext(securityContextMock);
}
});
return config;
}
然后,对我的资源进行的整个测试如下所示:
public class MyJerseyResourceTest extends JerseyTest {
@Test
public void helloWorld() throws Exception {
Response response = target("hello/world").request().get();
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
assertThat(response.getEntity()),isEqualTo("Hello Alice");
}
@Override
public Application configure() {
final SecurityContext securityContextMock = mock(SecurityContext.class);
when(securityContextMock.getUserPrincipal()).thenReturn(new Principal() {
@Override
public String getName() {
return "Alice";
}
});
ResourceConfig config = new ResourceConfig();
config.register(new ContainerRequestFilter(){
@Override
public void filter(final ContainerRequestContext containerRequestContext) throws IOException {
containerRequestContext.setSecurityContext(securityContextMock);
}
});
return config;
}
您是否有针对此问题的更明智的解决方案? 让我知道,并在下面写评论。
翻译自: https://www.javacodegeeks.com/2018/03/mocking-securitycontext-in-jersey-tests.html