Skip to content

Commit

Permalink
Task 55 : Implement JUnit tests for auth service and user service
Browse files Browse the repository at this point in the history
  • Loading branch information
Rapter1990 committed Jul 20, 2024
1 parent 6257b8c commit 1c0fec1
Show file tree
Hide file tree
Showing 27 changed files with 2,199 additions and 9 deletions.
6 changes: 6 additions & 0 deletions authservice/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,12 @@
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>


</dependencies>
<dependencyManagement>
<dependencies>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package com.springbootmicroservices.authservice.model.auth.dto.request;

import jakarta.validation.constraints.NotBlank;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.*;

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class LoginRequest {

@NotBlank
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.springbootmicroservices.authservice.base;

import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public abstract class AbstractBaseServiceTest {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.springbootmicroservices.authservice.base;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@AutoConfigureMockMvc
public class AbstractRestControllerTest {

@Autowired
protected MockMvc mockMvc;

@Autowired
protected ObjectMapper objectMapper;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package com.springbootmicroservices.authservice.controller;

import com.springbootmicroservices.authservice.base.AbstractRestControllerTest;
import com.springbootmicroservices.authservice.model.auth.dto.request.LoginRequest;
import com.springbootmicroservices.authservice.model.auth.dto.request.RegisterRequest;
import com.springbootmicroservices.authservice.model.auth.dto.request.TokenInvalidateRequest;
import com.springbootmicroservices.authservice.model.auth.dto.request.TokenRefreshRequest;
import com.springbootmicroservices.authservice.model.auth.dto.response.TokenResponse;
import com.springbootmicroservices.authservice.model.common.dto.response.CustomResponse;
import com.springbootmicroservices.authservice.service.LogoutService;
import com.springbootmicroservices.authservice.service.RefreshTokenService;
import com.springbootmicroservices.authservice.service.RegisterService;
import com.springbootmicroservices.authservice.service.UserLoginService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

class AuthControllerTest extends AbstractRestControllerTest {

@MockBean
private RegisterService registerService;

@MockBean
private UserLoginService userLoginService;

@MockBean
private RefreshTokenService refreshTokenService;

@MockBean
private LogoutService logoutService;

@Test
void registerAdmin_ValidRequest_ReturnsSuccess() throws Exception {

// Given
RegisterRequest registerRequest = RegisterRequest.builder()
.email("[email protected]")
.password("validPassword123")
.firstName("John")
.lastName("Doe")
.phoneNumber("1234567890100")
.role("user")
.build();

// When & Then
mockMvc.perform(post("/api/v1/authentication/users/register")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(registerRequest)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.isSuccess").value(true))
.andExpect(jsonPath("$.httpStatus").value("OK"));

// Verify
verify(registerService, times(1)).registerUser(any(RegisterRequest.class));

}

@Test
void loginUser_ValidRequest_ReturnsTokenResponse() throws Exception {

// Given
LoginRequest loginRequest = LoginRequest.builder()
.email("[email protected]")
.password("validPassword123")
.build();

TokenResponse tokenResponse = TokenResponse.builder()
.accessToken("newAccessToken")
.accessTokenExpiresAt(System.currentTimeMillis() + 3600)
.refreshToken("newRefreshToken")
.build();

CustomResponse<TokenResponse> expectedResponse = CustomResponse.successOf(tokenResponse);

// When
when(userLoginService.login(any(LoginRequest.class))).thenReturn(expectedResponse);

// Then
mockMvc.perform(post("/api/v1/authentication/users/login")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(loginRequest)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.isSuccess").value(true))
.andExpect(jsonPath("$.httpStatus").value("OK"))
.andExpect(jsonPath("$.response.accessToken").value("newAccessToken"));

// Verify
verify(userLoginService, times(1)).login(any(LoginRequest.class));

}

@Test
void refreshToken_ValidRequest_ReturnsTokenResponse() throws Exception {

// Given
TokenRefreshRequest tokenRefreshRequest = TokenRefreshRequest.builder()
.refreshToken("validRefreshToken")
.build();

TokenResponse tokenResponse = TokenResponse.builder()
.accessToken("newAccessToken")
.accessTokenExpiresAt(System.currentTimeMillis() + 3600)
.refreshToken("newRefreshToken")
.build();

CustomResponse<TokenResponse> expectedResponse = CustomResponse.successOf(tokenResponse);

// When
when(refreshTokenService.refreshToken(any(TokenRefreshRequest.class))).thenReturn(expectedResponse);

// Then
mockMvc.perform(post("/api/v1/authentication/users/refresh-token")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(tokenRefreshRequest)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.isSuccess").value(true))
.andExpect(jsonPath("$.httpStatus").value("OK"))
.andExpect(jsonPath("$.response.accessToken").value("newAccessToken"));

verify(refreshTokenService, times(1)).refreshToken(any(TokenRefreshRequest.class));
}

@Test
void logout_ValidRequest_ReturnsSuccess() throws Exception {

// Given
TokenInvalidateRequest tokenInvalidateRequest = TokenInvalidateRequest.builder()
.accessToken("validAccessToken")
.refreshToken("validRefreshToken")
.build();

// When & Then
mockMvc.perform(post("/api/v1/authentication/users/logout")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(tokenInvalidateRequest)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.isSuccess").value(true))
.andExpect(jsonPath("$.httpStatus").value("OK"));

// Verify
verify(logoutService, times(1)).logout(any(TokenInvalidateRequest.class));

}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package com.springbootmicroservices.authservice.exception;

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

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

import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;

import java.time.LocalDateTime;
import java.util.Collections;

public class CustomErrorTest {

@Test
void testCustomErrorBuilder_WithAllFields() {

LocalDateTime now = LocalDateTime.now();
CustomError.CustomSubError subError = CustomError.CustomSubError.builder()
.message("Sub error message")
.field("field")
.value("value")
.type("type")
.build();

CustomError customError = CustomError.builder()
.time(now)
.httpStatus(HttpStatus.BAD_REQUEST)
.header(CustomError.Header.VALIDATION_ERROR.getName())
.message("Main error message")
.subErrors(Collections.singletonList(subError))
.build();

assertNotNull(customError);
assertEquals(now, customError.getTime());
assertEquals(HttpStatus.BAD_REQUEST, customError.getHttpStatus());
assertEquals(CustomError.Header.VALIDATION_ERROR.getName(), customError.getHeader());
assertEquals("Main error message", customError.getMessage());
assertFalse(customError.getIsSuccess());
assertNotNull(customError.getSubErrors());
assertEquals(1, customError.getSubErrors().size());
assertEquals(subError, customError.getSubErrors().get(0));
}

@Test
void testCustomErrorBuilder_DefaultValues() {
CustomError customError = CustomError.builder().build();

assertNotNull(customError);
assertNotNull(customError.getTime());
assertEquals(false, customError.getIsSuccess());
assertNull(customError.getHttpStatus());
assertNull(customError.getHeader());
assertNull(customError.getMessage());
assertNull(customError.getSubErrors());
}

@Test
void testCustomSubErrorBuilder_WithAllFields() {
CustomError.CustomSubError subError = CustomError.CustomSubError.builder()
.message("Sub error message")
.field("field")
.value("value")
.type("type")
.build();

assertNotNull(subError);
assertEquals("Sub error message", subError.getMessage());
assertEquals("field", subError.getField());
assertEquals("value", subError.getValue());
assertEquals("type", subError.getType());
}

@Test
void testCustomSubErrorBuilder_DefaultValues() {
CustomError.CustomSubError subError = CustomError.CustomSubError.builder().build();

assertNotNull(subError);
assertNull(subError.getMessage());
assertNull(subError.getField());
assertNull(subError.getValue());
assertNull(subError.getType());
}

@Test
void testCustomErrorHeaderEnum() {
assertEquals("API ERROR", CustomError.Header.API_ERROR.getName());
assertEquals("ALREADY EXIST", CustomError.Header.ALREADY_EXIST.getName());
assertEquals("NOT EXIST", CustomError.Header.NOT_FOUND.getName());
assertEquals("VALIDATION ERROR", CustomError.Header.VALIDATION_ERROR.getName());
assertEquals("DATABASE ERROR", CustomError.Header.DATABASE_ERROR.getName());
assertEquals("PROCESS ERROR", CustomError.Header.PROCESS_ERROR.getName());
assertEquals("AUTH ERROR", CustomError.Header.AUTH_ERROR.getName());
}

}
Loading

0 comments on commit 1c0fec1

Please sign in to comment.