Skip to content

Commit aee15cd

Browse files
committed
Task 57 : Implement filter, serializer and domain JUnit tests for product service, auth service and user service
1 parent 03b8c0d commit aee15cd

File tree

13 files changed

+802
-9
lines changed

13 files changed

+802
-9
lines changed

authservice/src/test/java/com/springbootmicroservices/authservice/model/auth/TokenTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import org.junit.jupiter.api.Test;
66
import org.springframework.util.StringUtils;
77

8-
public class TokenTest {
8+
class TokenTest {
99

1010
@Test
1111
void testTokenBuilder_WithAllFields() {

authservice/src/test/java/com/springbootmicroservices/authservice/model/auth/UserTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import com.springbootmicroservices.authservice.model.auth.enums.UserType;
77
import org.junit.jupiter.api.Test;
88

9-
public class UserTest {
9+
class UserTest {
1010

1111
@Test
1212
void testUserBuilder_WithAllFields() {

authservice/src/test/java/com/springbootmicroservices/authservice/security/CustomAuthenticationEntryPointTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
import static org.mockito.ArgumentMatchers.any;
2828
import static org.mockito.Mockito.*;
2929

30-
public class CustomAuthenticationEntryPointTest {
30+
class CustomAuthenticationEntryPointTest {
3131

3232
private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
3333

productservice/src/main/java/com/springbootmicroservices/productservice/filter/CustomBearerTokenAuthenticationFilter.java

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,4 @@ protected void doFilterInternal(@NonNull final HttpServletRequest httpServletReq
7070
filterChain.doFilter(httpServletRequest, httpServletResponse);
7171
}
7272

73-
74-
private Jwt convertJwtRecordToJwt(JwtRecord jwtRecord) {
75-
return new Jwt(jwtRecord.tokenValue(), jwtRecord.issuedAt(), jwtRecord.expiresAt(), jwtRecord.headers(), jwtRecord.claims());
76-
}
77-
7873
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
package com.springbootmicroservices.productservice.exception;
2+
3+
import com.springbootmicroservices.productservice.base.AbstractRestControllerTest;
4+
import com.springbootmicroservices.productservice.model.common.CustomError;
5+
import jakarta.validation.ConstraintViolation;
6+
import jakarta.validation.ConstraintViolationException;
7+
import jakarta.validation.Path;
8+
import org.junit.jupiter.api.Test;
9+
import org.mockito.InjectMocks;
10+
import org.springframework.http.HttpStatus;
11+
import org.springframework.http.ResponseEntity;
12+
import org.springframework.validation.BindingResult;
13+
import org.springframework.validation.FieldError;
14+
import org.springframework.validation.ObjectError;
15+
import org.springframework.web.bind.MethodArgumentNotValidException;
16+
17+
import java.time.LocalDateTime;
18+
import java.util.Collections;
19+
import java.util.List;
20+
import java.util.Set;
21+
22+
import static org.assertj.core.api.Assertions.assertThat;
23+
import static org.junit.jupiter.api.Assertions.*;
24+
import static org.mockito.Mockito.mock;
25+
import static org.mockito.Mockito.when;
26+
27+
class GlobalExceptionHandlerTest extends AbstractRestControllerTest {
28+
29+
@InjectMocks
30+
private GlobalExceptionHandler globalExceptionHandler;
31+
32+
@Test
33+
void givenMethodArgumentNotValidException_whenHandleMethodArgumentNotValid_thenRespondWithBadRequest() {
34+
35+
// Given
36+
BindingResult bindingResult = mock(BindingResult.class);
37+
MethodArgumentNotValidException ex = new MethodArgumentNotValidException(null, bindingResult);
38+
FieldError fieldError = new FieldError("objectName", "fieldName", "error message");
39+
List<ObjectError> objectErrors = Collections.singletonList(fieldError);
40+
41+
when(bindingResult.getAllErrors()).thenReturn(objectErrors);
42+
43+
CustomError expectedError = CustomError.builder()
44+
.httpStatus(HttpStatus.BAD_REQUEST)
45+
.header(CustomError.Header.VALIDATION_ERROR.getName())
46+
.message("Validation failed")
47+
.subErrors(Collections.singletonList(
48+
CustomError.CustomSubError.builder()
49+
.field("fieldName")
50+
.message("error message")
51+
.build()))
52+
.build();
53+
54+
// When
55+
ResponseEntity<Object> responseEntity = globalExceptionHandler.handleMethodArgumentNotValid(ex);
56+
57+
// Then
58+
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
59+
CustomError actualError = (CustomError) responseEntity.getBody();
60+
checkCustomError(expectedError, actualError);
61+
62+
}
63+
64+
@Test
65+
void givenConstraintViolationException_whenHandlePathVariableErrors_thenRespondWithBadRequest() {
66+
67+
// Given
68+
ConstraintViolation<String> mockViolation = mock(ConstraintViolation.class);
69+
Path mockPath = mock(Path.class);
70+
Set<ConstraintViolation<?>> violations = Set.of(mockViolation);
71+
ConstraintViolationException mockException = new ConstraintViolationException(violations);
72+
73+
CustomError.CustomSubError subError = CustomError.CustomSubError.builder()
74+
.message("must not be null")
75+
.field("")
76+
.value("invalid value")
77+
.type("String") // Default to String if getRootBeanClass() is null
78+
.build();
79+
80+
CustomError expectedError = CustomError.builder()
81+
.time(LocalDateTime.now())
82+
.httpStatus(HttpStatus.BAD_REQUEST)
83+
.header(CustomError.Header.VALIDATION_ERROR.getName())
84+
.message("Constraint violation")
85+
.subErrors(Collections.singletonList(subError))
86+
.build();
87+
88+
// When
89+
when(mockViolation.getMessage()).thenReturn("must not be null");
90+
when(mockViolation.getPropertyPath()).thenReturn(mockPath);
91+
when(mockPath.toString()).thenReturn("field");
92+
when(mockViolation.getInvalidValue()).thenReturn("invalid value");
93+
when(mockViolation.getRootBeanClass()).thenReturn(String.class); // Ensure this does not return null
94+
95+
// Then
96+
ResponseEntity<Object> responseEntity = globalExceptionHandler.handlePathVariableErrors(mockException);
97+
98+
CustomError actualError = (CustomError) responseEntity.getBody();
99+
100+
// Verify
101+
checkCustomError(expectedError, actualError);
102+
103+
}
104+
105+
@Test
106+
void givenRuntimeException_whenHandleRuntimeException_thenRespondWithNotFound() {
107+
108+
// Given
109+
RuntimeException ex = new RuntimeException("Runtime exception message");
110+
111+
CustomError expectedError = CustomError.builder()
112+
.httpStatus(HttpStatus.NOT_FOUND)
113+
.header(CustomError.Header.API_ERROR.getName())
114+
.message("Runtime exception message")
115+
.build();
116+
117+
// When
118+
ResponseEntity<?> responseEntity = globalExceptionHandler.handleRuntimeException(ex);
119+
120+
// Then
121+
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
122+
123+
CustomError actualError = (CustomError) responseEntity.getBody();
124+
checkCustomError(expectedError, actualError);
125+
126+
}
127+
128+
@Test
129+
void givenProductAlreadyExistException_whenHandleProductAlreadyExistException_thenRespondWithConflict() {
130+
131+
// Given
132+
ProductAlreadyExistException ex = new ProductAlreadyExistException();
133+
134+
CustomError expectedError = CustomError.builder()
135+
.httpStatus(HttpStatus.CONFLICT)
136+
.header(CustomError.Header.ALREADY_EXIST.getName())
137+
.message("Product already exist!\n")
138+
.isSuccess(false)
139+
.build();
140+
141+
// When
142+
ResponseEntity<CustomError> responseEntity = globalExceptionHandler.handleProductAlreadyExistException(ex);
143+
144+
// Then
145+
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
146+
147+
CustomError actualError = responseEntity.getBody();
148+
checkCustomError(expectedError, actualError);
149+
150+
}
151+
152+
@Test
153+
void givenProductNotFoundException_whenHandleProductNotFoundException_thenRespondWithNotFound() {
154+
155+
// Given
156+
ProductNotFoundException ex = new ProductNotFoundException();
157+
158+
CustomError expectedError = CustomError.builder()
159+
.httpStatus(HttpStatus.NOT_FOUND)
160+
.header(CustomError.Header.NOT_FOUND.getName())
161+
.message("Product not found!\n")
162+
.isSuccess(false)
163+
.build();
164+
165+
// When
166+
ResponseEntity<CustomError> responseEntity = globalExceptionHandler.handleProductNotFoundException(ex);
167+
168+
// Then
169+
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
170+
171+
CustomError actualError = responseEntity.getBody();
172+
checkCustomError(expectedError, actualError);
173+
}
174+
175+
176+
177+
private void checkCustomError(CustomError expectedError, CustomError actualError) {
178+
179+
assertThat(actualError).isNotNull();
180+
assertThat(actualError.getTime()).isNotNull();
181+
assertThat(actualError.getHeader()).isEqualTo(expectedError.getHeader());
182+
assertThat(actualError.getIsSuccess()).isEqualTo(expectedError.getIsSuccess());
183+
184+
if (expectedError.getMessage() != null) {
185+
assertThat(actualError.getMessage()).isEqualTo(expectedError.getMessage());
186+
}
187+
188+
if (expectedError.getSubErrors() != null) {
189+
assertThat(actualError.getSubErrors().size()).isEqualTo(expectedError.getSubErrors().size());
190+
if (!expectedError.getSubErrors().isEmpty()) {
191+
assertThat(actualError.getSubErrors().get(0).getMessage()).isEqualTo(expectedError.getSubErrors().get(0).getMessage());
192+
assertThat(actualError.getSubErrors().get(0).getField()).isEqualTo(expectedError.getSubErrors().get(0).getField());
193+
assertThat(actualError.getSubErrors().get(0).getValue()).isEqualTo(expectedError.getSubErrors().get(0).getValue());
194+
assertThat(actualError.getSubErrors().get(0).getType()).isEqualTo(expectedError.getSubErrors().get(0).getType());
195+
}
196+
}
197+
}
198+
199+
}
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
package com.springbootmicroservices.productservice.model.auth;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class TokenTest {
8+
9+
@Test
10+
void testTokenBuilder_WithAllFields() {
11+
12+
// Given
13+
String accessToken = "sampleAccessToken";
14+
Long accessTokenExpiresAt = System.currentTimeMillis() + 3600;
15+
String refreshToken = "sampleRefreshToken";
16+
17+
// When
18+
Token token = Token.builder()
19+
.accessToken(accessToken)
20+
.accessTokenExpiresAt(accessTokenExpiresAt)
21+
.refreshToken(refreshToken)
22+
.build();
23+
24+
// Then
25+
assertNotNull(token);
26+
assertEquals(accessToken, token.getAccessToken());
27+
assertEquals(accessTokenExpiresAt, token.getAccessTokenExpiresAt());
28+
assertEquals(refreshToken, token.getRefreshToken());
29+
30+
}
31+
32+
@Test
33+
void testTokenBuilder_DefaultValues() {
34+
35+
// When
36+
Token token = Token.builder().build();
37+
38+
// Then
39+
assertNotNull(token);
40+
assertNull(token.getAccessToken());
41+
assertNull(token.getAccessTokenExpiresAt());
42+
assertNull(token.getRefreshToken());
43+
44+
}
45+
46+
@Test
47+
void testIsBearerToken_WithValidBearerToken() {
48+
49+
// Given
50+
String authorizationHeader = "Bearer sampleAccessToken";
51+
52+
// When
53+
boolean result = Token.isBearerToken(authorizationHeader);
54+
55+
// Then
56+
assertTrue(result);
57+
58+
}
59+
60+
@Test
61+
void testIsBearerToken_WithInvalidBearerToken() {
62+
63+
// Given
64+
String authorizationHeader = "sampleAccessToken";
65+
66+
// When
67+
boolean result = Token.isBearerToken(authorizationHeader);
68+
69+
// Then
70+
assertFalse(result);
71+
72+
}
73+
74+
@Test
75+
void testIsBearerToken_WithEmptyHeader() {
76+
77+
// Given
78+
String authorizationHeader = "";
79+
80+
// When
81+
boolean result = Token.isBearerToken(authorizationHeader);
82+
83+
// Then
84+
assertFalse(result);
85+
86+
}
87+
88+
@Test
89+
void testGetJwt_WithBearerToken() {
90+
91+
// Given
92+
String authorizationHeader = "Bearer sampleAccessToken";
93+
94+
// When
95+
String jwt = Token.getJwt(authorizationHeader);
96+
97+
// Then
98+
assertEquals("sampleAccessToken", jwt);
99+
100+
}
101+
102+
@Test
103+
void testGetJwt_WithInvalidTokenFormat() {
104+
105+
// Given
106+
String authorizationHeader = "sampleAccessToken";
107+
108+
// When
109+
String jwt = Token.getJwt(authorizationHeader);
110+
111+
// Then
112+
assertEquals("sampleAccessToken", jwt);
113+
114+
}
115+
116+
@Test
117+
void testGetJwt_WithEmptyHeader() {
118+
119+
// Given
120+
String authorizationHeader = "";
121+
122+
// When
123+
String jwt = Token.getJwt(authorizationHeader);
124+
125+
// Then
126+
assertEquals("", jwt);
127+
128+
}
129+
130+
}

0 commit comments

Comments
 (0)