Home » Java » Enterprise Java » Mocking SecurityContext in Jersey Tests

About Sandra Parsick

Sandra Parsick
Sandra is freelance Software Developer. She develops Java enterprise software since 2008. She also interests in the software craftsmanship approach and continuous integration.

Mocking SecurityContext in Jersey Tests

Jersey has a great possibility to write integration test for REST-APIs, written with Jersey. Just extend the class JerseyTest and go for it.

I ran in an issue, where I had to mock a SecurityContext, so that the SecurityContext includes a special UserPrincipal. The challenge is that Jersey wraps the SecurityContext in an own class SecurityContextInjectee in tests. So I have to add my SecurityContext Mock to this Jersey’s wrapper class. Let me demonstrate it in an example.

Let say I have the following Jersey Resource:

@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();
  }

}

In my test, I have to mock the SecurityContext, so that a predefined user principal can be used during the tests. I use Mockito as mocking framework. My mock looks like the following one

final SecurityContext securityContextMock = mock(SecurityContext.class);
       when(securityContextMock.getUserPrincipal()).thenReturn(new Principal() {
          @Override
          public String getName() {
              return "Alice";
          }
      });

For adding this mocked SecurityContext to the wrapper class SecurityContextInjectee, I have to configure a ResourceConfig with a modified ContainerRequestContext in my Jersey Test. The mocked SecurityContext can be set in this modified ContainerRequestContext and then it will be used in the wrapper class:

@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;
   }

Then, the whole test for my resource looks like the following one:

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;
   }

Do you have a smarter solution for this problem? Let me know it and write a comment below.

Published on Java Code Geeks with permission by Sandra Parsick, partner at our JCG program. See the original article here: Mocking SecurityContext in Jersey Tests

Opinions expressed by Java Code Geeks contributors are their own.

(+1 rating, 1 votes)
You need to be a registered member to rate this.
1 Comment Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Carl Ellis Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Carl Ellis
Member
Carl Ellis

A good article that could be a little bitter with the appropriate Maven/Gradle dependencies and imports for the Java classes involved.