DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • A Beginner’s Guide to Playwright: End-to-End Testing Made Easy
  • Automating E2E Tests With MFA: Streamline Your Testing Workflow
  • Exploring Cloud-Based Testing With the Elastic Execution Grid
  • Integrating Selenium With Amazon S3 for Test Artifact Management

Trending

  • Maximizing Productivity: GitHub Copilot With Custom Instructions in VS Code
  • How to Format Articles for DZone
  • Replacing Legacy Systems With Data Streaming: The Strangler Fig Approach
  • Beyond the Glass Slab: How AI Voice Assistants are Morphing Into Our Real-Life JARVIS
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Mocking SecurityContext in Jersey Tests

Mocking SecurityContext in Jersey Tests

Jersey can be used to write integration tests for REST APIs. In this tutorial, you'll learn how to mock a SecurityContext in your tests.

By 
Sandra Parsick user avatar
Sandra Parsick
·
Apr. 02, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
8.7K Views

Join the DZone community and get the full member experience.

Join For Free

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

I ran into 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.

Testing

Published at DZone with permission of Sandra Parsick, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Beginner’s Guide to Playwright: End-to-End Testing Made Easy
  • Automating E2E Tests With MFA: Streamline Your Testing Workflow
  • Exploring Cloud-Based Testing With the Elastic Execution Grid
  • Integrating Selenium With Amazon S3 for Test Artifact Management

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: