How to mock jwt token in junit

How to mock JWT token in JUnit

JWT (JSON Web Token) is a popular method for representing claims securely between two parties. When writing unit tests for code that relies on JWT tokens, mocking the token can be useful to simulate different scenarios without the need for actual token generation. Here’s how you can mock a JWT token in JUnit:

  1. Add the necessary dependencies to your project. You will need JUnit and a mocking framework like Mockito.
  2. Create a mock JWT token using a library like jjwt. Let’s assume you have a method that generates a JWT token:
  3.     
    import io.jsonwebtoken.Claims;
    import io.jsonwebtoken.JwtBuilder;
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    
    public class TokenGenerator {
        public String generateToken(String username, String role) {
            JwtBuilder builder = Jwts.builder().setSubject(username)
                    .claim("role", role)
                    .signWith(SignatureAlgorithm.HS256, "secret-key");
            return builder.compact();
        }
    }
        
        
  4. In your JUnit test class, mock the JWT token by creating a fake token using the same library. For example:
  5.     
    import org.junit.Test;
    import org.mockito.Mock;
    import org.mockito.Mockito;
    import static org.mockito.Mockito.*;
    
    public class MyTestClass {
        @Mock
        TokenGenerator tokenGenerator;
        
        @Test
        public void testWithMockedJWTToken() {
            String mockToken = Jwts.builder().setSubject("mockuser")
                    .claim("role", "admin")
                    .signWith(SignatureAlgorithm.HS256, "mock-key")
                    .compact();
            
            Mockito.when(tokenGenerator.generateToken(anyString(), anyString())).thenReturn(mockToken);
            
            // Write your test code here
            // You can now call methods that rely on the JWT token and it will use the mock token
            
            verify(tokenGenerator, times(1)).generateToken(anyString(), anyString());
        }
    }
        
        
  6. In the above example, we use Mockito to mock the TokenGenerator class and override the generateToken() method to return the mock token. This ensures that whenever the generateToken() method is called, it will return the mock token instead of generating a real token. The verify() method checks if the generateToken() method was called exactly once.
  7. You can now proceed with writing your test code, making calls to methods that rely on the JWT token. The mock token will be used instead of a real token.

Leave a comment