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

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.




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store