VOOZH about

URL: https://www.geeksforgeeks.org/java/testing-spring-security-auth-with-junit/

⇱ Testing Spring Security Auth with JUnit - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Testing Spring Security Auth with JUnit

Last Updated : 23 Jul, 2025

Here we are going to learn how to use InMemoryDaoImpl to verify Spring security authentication using a JUnit test case and how to programmatically create a fully complete authentication object and then utilize it in an application.

SecurityContextHolder: Spring security is built on the concept of a security context, which is somewhat static. This simply implies that you don't have to inject its reference into your spring container beans or classes. The SecurityContextHolder.getContext() function may be used to get the spring context at any moment.This context contains a reference to the real principal or user, whose access permissions we must verify.

Unit test Spring Security: We will be creating a Maven project and writing very little code so one can focus on testing only the aspects of authentication that are relevant to this topic. Then I'll construct a simple sample service class with only one method that requires "ROLE USER" to access. If you try to use this function without having "ROLE USER," you'll get an AccessDeniedException as predicted. Isn't it straightforward?

The project structure is as follows: 

Let's make a Java project with the following command:

Console

$ mvn archetype:generate -DgroupId=com.geeksforgeeks
 -DartifactId=SpringPasswordHashingDemo
 -DarchetypeArtifactId=maven-archetype-quickstart 
 -DinteractiveMode=false
👁 Image
 

To make project eclipse supported, edit the pom.xml with the following dependencies and run the command mvn:eclipse:eclipse.

File: pom.xml


Step 2: Make a file for security configuration.

By now we have created a file called application-security.xml and placed the security configuration inside.

File: application-security.xml


Step 3: Create a secured method

File: DemoService.java


Step 4: Use JUnit to test the authentication

In JUnit tests, we'll programmatically establish the spring context and then access users by username from the default user information service. In our instance, it's an in-memory implementation, which may differ from a JDBC-based user information service or a bespoke user details service in your situation. As a result, please adjust the lookup appropriately.

We'll test a variety of situations, including valid user, invalid user, and invalid role, among others. You have the option to add or delete situations based on your preferences.

File: TestDemoService.java


Output: Now we will see all test cases are running as depicted via the visual aid below shown as follows: 

👁 Image
 
👁 Image
 
Comment
Article Tags: