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:
- Add the necessary dependencies to your project. You will need JUnit and a mocking framework like Mockito.
- Create a mock JWT token using a library like jjwt. Let’s assume you have a method that generates a JWT token:
- In your JUnit test class, mock the JWT token by creating a fake token using the same library. For example:
- 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.
- 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.
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();
}
}
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());
}
}
- How to display different navbar component for different reactjs pages
- How to check datatable column value is null or empty in c# linq
- How to get key value from nested json object in c#
- How to know which dependency changed in useeffect
- How to add a symlink to it from project’s node_modules/
- How to delete selected row from gridview and database in c#
- How to get safe area height in swift
- How to mock axios instance in jest