[Spring Boot] How to stub @AuthenticationPrincipal argument with Spring-Security in Unit Tests

Jay Kim
1 min readSep 13, 2021

--

There may be some situations where user information is required as part of business logic. Quite often, this process takes place after authentication. In this article, let us find out how user information can be obtained as well as how to write unit tests for such cases.

First of all, let us look at a sample controller below. Using Spring Security it is possible to obtain information of the current logged-in user by using @AuthenticationPrincipal.

For the purpose of testing, we hope to invoke /username endpoint to get the username. But unlike @RequestParam or @PathVariable (where we can inject right into the URL) or @RequestBody (where we can pass in the content and content type) injecting user information might not seem natural.

When using MockMvc, it is possible to resolve custom argument and let us see how to do that. For this, let us create a custom argument resolver class where it returns a pre-defined user information. This seems adequate because when using JWT token, the token is likely to be verified before the reaching the implementation of the /username endpoint.

Lastly, the custom argument resolver class can be used when setting up MockMvc with setCustomArgumentResolvers() method.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response