Untitled

mail@pastecode.io avatar
unknown
plain_text
10 days ago
4.8 kB
2
Indexable
Never
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(MockitoExtension.class)
public class JwtServiceTest {

    @Mock
    private KeycloakJwt keycloakJwt;

    @Mock
    private RoleGroupService roleGroupService;

    @Mock
    private InternalJwt internalJwt;

    @InjectMocks
    private JwtService jwtService;

    private String token;
    private UserEntity user;

    @BeforeEach
    void setUp() {
        token = "mockToken";
        user = new UserEntity();
        user.setId(1L);
        user.setUserName("testUser");
    }

    @Test
    void convertWithToken_ShouldReturnNewToken_WhenValidTokenAndUserAreProvided() {
        // Giả lập JWT claims
        Claims claims = mock(Claims.class);
        when(claims.get(JwtConstant.PREFERRED_NAME_CLAIM)).thenReturn("testUser");
        when(claims.get(JwtConstant.EMAIL_CLAIM)).thenReturn("test@test.com");
        when(claims.get(JwtConstant.GIVEN_NAME_CLAIM)).thenReturn("Test");
        when(claims.get(JwtConstant.IAT_KEY_CLAIM)).thenReturn(Instant.now().getEpochSecond());
        when(claims.get(JwtConstant.EXP_KEY_CLAIM)).thenReturn(Instant.now().plusSeconds(3600).getEpochSecond());

        Jws<Claims> jws = mock(Jws.class);
        when(jws.getBody()).thenReturn(claims);
        when(keycloakJwt.buildJwtParser().parseClaimsJws(token)).thenReturn(jws);

        // Giả lập RoleGroupService
        UserPermissionData role1 = new UserPermissionData("ROLE_USER");
        UserPermissionData role2 = new UserPermissionData("ROLE_ADMIN");
        when(roleGroupService.getAllByUserId(user.getId())).thenReturn(List.of(role1, role2));

        // Giả lập JWT builder
        JwtBuilder jwtBuilder = mock(JwtBuilder.class);
        when(jwtBuilder.setSubject(anyString())).thenReturn(jwtBuilder);
        when(jwtBuilder.claim(anyString(), any())).thenReturn(jwtBuilder);
        when(jwtBuilder.setIssuedAt(any(Date.class))).thenReturn(jwtBuilder);
        when(jwtBuilder.setExpiration(any(Date.class))).thenReturn(jwtBuilder);
        when(jwtBuilder.setIssuer(anyString())).thenReturn(jwtBuilder);
        when(jwtBuilder.compact()).thenReturn("newJwtToken");

        when(internalJwt.buildJwtBuilder()).thenReturn(jwtBuilder);

        // Gọi phương thức convertWithToken
        String result = jwtService.convertWithToken(token, user);

        // Kiểm tra kết quả trả về
        assertNotNull(result);
        assertEquals("newJwtToken", result);
    }

    @Test
    void convertWithToken_ShouldThrowBadRequestException_WhenJwtParsingFails() {
        // Giả lập exception khi parsing JWT
        when(keycloakJwt.buildJwtParser().parseClaimsJws(token)).thenThrow(new RuntimeException("Invalid Token"));

        // Kiểm tra ngoại lệ BadRequestException
        Exception exception = assertThrows(BadRequestException.class, () -> {
            jwtService.convertWithToken(token, user);
        });

        assertEquals(IAMErrorCode.JWT_CONVERT_ERROR, exception.getMessage());
    }

    @Test
    void convertWithToken_ShouldThrowBadRequestException_WhenRoleGroupServiceFails() {
        // Giả lập JWT claims hợp lệ
        Claims claims = mock(Claims.class);
        when(claims.get(JwtConstant.PREFERRED_NAME_CLAIM)).thenReturn("testUser");
        when(claims.get(JwtConstant.EMAIL_CLAIM)).thenReturn("test@test.com");
        when(claims.get(JwtConstant.GIVEN_NAME_CLAIM)).thenReturn("Test");
        when(claims.get(JwtConstant.IAT_KEY_CLAIM)).thenReturn(Instant.now().getEpochSecond());
        when(claims.get(JwtConstant.EXP_KEY_CLAIM)).thenReturn(Instant.now().plusSeconds(3600).getEpochSecond());

        Jws<Claims> jws = mock(Jws.class);
        when(jws.getBody()).thenReturn(claims);
        when(keycloakJwt.buildJwtParser().parseClaimsJws(token)).thenReturn(jws);

        // Giả lập ngoại lệ khi gọi RoleGroupService
        when(roleGroupService.getAllByUserId(user.getId())).thenThrow(new RuntimeException("Role Group Service Error"));

        // Kiểm tra ngoại lệ BadRequestException
        Exception exception = assertThrows(BadRequestException.class, () -> {
            jwtService.convertWithToken(token, user);
        });

        assertEquals(IAMErrorCode.JWT_CONVERT_ERROR, exception.getMessage());
    }
}
Leave a Comment