-
Notifications
You must be signed in to change notification settings - Fork 11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Added tests for custom exceptions #556
base: develop
Are you sure you want to change the base?
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,7 @@ | |
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import com.softserveinc.dokazovi.dto.payload.LoginRequest; | ||
import com.softserveinc.dokazovi.entity.UserEntity; | ||
import com.softserveinc.dokazovi.exception.BadRequestException; | ||
import com.softserveinc.dokazovi.security.TokenProvider; | ||
import com.softserveinc.dokazovi.service.ProviderService; | ||
import com.softserveinc.dokazovi.service.UserService; | ||
|
@@ -26,6 +27,8 @@ | |
|
||
import static com.softserveinc.dokazovi.controller.EndPoints.AUTH; | ||
import static com.softserveinc.dokazovi.controller.EndPoints.AUTH_LOGIN; | ||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
import static org.junit.jupiter.api.Assertions.assertTrue; | ||
import static org.mockito.ArgumentMatchers.any; | ||
import static org.mockito.ArgumentMatchers.anyString; | ||
import static org.mockito.Mockito.times; | ||
|
@@ -37,6 +40,8 @@ | |
@MockitoSettings(strictness = Strictness.LENIENT) | ||
class AuthControllerTest { | ||
|
||
|
||
|
||
private MockMvc mockMvc; | ||
@Mock | ||
private TokenProvider tokenProvider; | ||
|
@@ -51,50 +56,95 @@ class AuthControllerTest { | |
@InjectMocks | ||
private AuthController authController; | ||
|
||
private static final String EMAIL = "[email protected]"; | ||
private static final String PASSWORD = "user"; | ||
private static final String TOKEN = "950c9760-805e-449c-a966-2d0d5ebd86f4"; | ||
private static final String URI = AUTH + AUTH_LOGIN; | ||
public static final String BAD_REQUEST_MESSAGE = "Please confirm your email!"; | ||
|
||
@BeforeEach | ||
public void init() { | ||
this.mockMvc = MockMvcBuilders | ||
.standaloneSetup(authController) | ||
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver()) | ||
.build(); | ||
LoginRequest loginRequest = new LoginRequest(); | ||
loginRequest.setEmail(EMAIL); | ||
loginRequest.setPassword(PASSWORD); | ||
} | ||
|
||
@Test | ||
void loginUser() throws Exception { | ||
String email = "[email protected]"; | ||
String password = "user"; | ||
LoginRequest loginRequest = createLoginRequest(EMAIL, PASSWORD); | ||
Authentication authentication = authenticate(loginRequest); | ||
V-Kaidash marked this conversation as resolved.
Show resolved
Hide resolved
|
||
UserEntity user = buildUserEntity(EMAIL, PASSWORD, true); | ||
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) | ||
.thenReturn(authentication); | ||
when(tokenProvider.createToken(any(Authentication.class))).thenReturn(TOKEN); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please make assertion on token value after post request. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. |
||
when(userService.findByEmail(anyString())).thenReturn(user); | ||
mockMvc.perform(MockMvcRequestBuilders.post(URI) | ||
.content(asJsonString(loginRequest)) | ||
.contentType(MediaType.APPLICATION_JSON) | ||
.accept(MediaType.APPLICATION_JSON)) | ||
.andExpect(status().isOk()); | ||
verify(authenticationManager, times(2)) | ||
.authenticate(any(UsernamePasswordAuthenticationToken.class)); | ||
verify(userService, times(1)) | ||
.findByEmail(anyString()); | ||
} | ||
V-Kaidash marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
@Test | ||
void loginUser_WhenEnabledFalse_ThrowException() throws Exception { | ||
LoginRequest loginRequest = createLoginRequest(EMAIL, PASSWORD); | ||
Authentication authentication = authenticate(loginRequest); | ||
UserEntity user = buildUserEntity(EMAIL, PASSWORD, false); | ||
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) | ||
.thenReturn(authentication); | ||
when(tokenProvider.createToken(any(Authentication.class))).thenReturn(TOKEN); | ||
when(userService.findByEmail(anyString())).thenReturn(user); | ||
mockMvc.perform(MockMvcRequestBuilders.post(URI) | ||
.content(asJsonString(loginRequest)) | ||
.contentType(MediaType.APPLICATION_JSON) | ||
.accept(MediaType.APPLICATION_JSON)) | ||
.andExpect(status().isBadRequest()) | ||
.andExpect(result -> | ||
assertTrue(result.getResolvedException() | ||
instanceof | ||
BadRequestException)) | ||
.andExpect(result -> | ||
assertEquals( | ||
BAD_REQUEST_MESSAGE, | ||
result.getResolvedException().getMessage())); | ||
verify(userService, times(1)) | ||
.findByEmail(anyString()); | ||
} | ||
|
||
private LoginRequest createLoginRequest(String email, String password) { | ||
LoginRequest loginRequest = new LoginRequest(); | ||
loginRequest.setEmail(email); | ||
loginRequest.setPassword(password); | ||
Authentication authentication = authenticationManager.authenticate( | ||
|
||
return loginRequest; | ||
} | ||
|
||
private Authentication authenticate(LoginRequest loginRequest) { | ||
return authenticationManager.authenticate( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. |
||
new UsernamePasswordAuthenticationToken( | ||
loginRequest.getEmail(), | ||
loginRequest.getPassword() | ||
) | ||
); | ||
String token = "950c9760-805e-449c-a966-2d0d5ebd86f4"; | ||
String uri = AUTH + AUTH_LOGIN; | ||
UserEntity user = UserEntity.builder() | ||
} | ||
|
||
private UserEntity buildUserEntity(String email, String password, boolean enabled) { | ||
return UserEntity.builder() | ||
.email(email) | ||
.password(password) | ||
.enabled(true) | ||
.enabled(enabled) | ||
.build(); | ||
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) | ||
.thenReturn(authentication); | ||
when(tokenProvider.createToken(any(Authentication.class))).thenReturn(token); | ||
when(userService.findByEmail(anyString())).thenReturn(user); | ||
mockMvc.perform(MockMvcRequestBuilders.post(uri) | ||
.content(asJsonString(loginRequest)) | ||
.contentType(MediaType.APPLICATION_JSON) | ||
.accept(MediaType.APPLICATION_JSON)) | ||
.andExpect(status().isOk()); | ||
verify(authenticationManager, times(2)) | ||
.authenticate(any(UsernamePasswordAuthenticationToken.class)); | ||
verify(userService, times(1)) | ||
.findByEmail(anyString()); | ||
} | ||
|
||
public static String asJsonString(final Object obj) { | ||
private String asJsonString(final Object obj) { | ||
try { | ||
return new ObjectMapper().writeValueAsString(obj); | ||
} catch (Exception e) { | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ | |
import com.softserveinc.dokazovi.entity.RoleEntity; | ||
import com.softserveinc.dokazovi.entity.UserEntity; | ||
import com.softserveinc.dokazovi.entity.enumerations.UserStatus; | ||
import com.softserveinc.dokazovi.exception.ResourceNotFoundException; | ||
import com.softserveinc.dokazovi.repositories.UserRepository; | ||
import org.junit.jupiter.api.Test; | ||
import org.junit.jupiter.api.extension.ExtendWith; | ||
|
@@ -17,6 +18,8 @@ | |
import java.util.Set; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
import static org.junit.jupiter.api.Assertions.assertThrows; | ||
import static org.mockito.ArgumentMatchers.any; | ||
import static org.mockito.ArgumentMatchers.anyString; | ||
import static org.mockito.Mockito.times; | ||
import static org.mockito.Mockito.verify; | ||
|
@@ -25,19 +28,12 @@ | |
@ExtendWith(MockitoExtension.class) | ||
class CustomUserDetailsServiceTest { | ||
|
||
@Mock | ||
private UserEntity userEntity; | ||
|
||
@Mock | ||
private UserRepository userRepository; | ||
|
||
@Mock | ||
private UserPrincipal userPrincipal; | ||
|
||
@InjectMocks | ||
private CustomUserDetailsService customUserDetailsService; | ||
|
||
|
||
@Test | ||
void loadUserByUsername() { | ||
String email = "[email protected]"; | ||
|
@@ -83,4 +79,16 @@ void loadUserById() { | |
verify(userRepository, times(1)).findById(id); | ||
assertEquals(email, resultUser.getUsername()); | ||
} | ||
|
||
@Test | ||
void loadUserById_UserNotFound_ThrowException() { | ||
Integer id = 0; | ||
Exception exception = assertThrows(ResourceNotFoundException.class, () -> | ||
customUserDetailsService.loadUserById(id) | ||
); | ||
String expectedMessage = String.format("%s not found with %s : '%s'", "User", "id", id); | ||
assertEquals(expectedMessage, exception.getMessage()); | ||
verify(userRepository, times(1)) | ||
.findById(any(Integer.class)); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -62,6 +62,7 @@ | |
import static org.mockito.ArgumentMatchers.anyBoolean; | ||
import static org.mockito.ArgumentMatchers.anySet; | ||
import static org.mockito.ArgumentMatchers.eq; | ||
import static org.mockito.Mockito.never; | ||
import static org.mockito.Mockito.times; | ||
import static org.mockito.Mockito.verify; | ||
import static org.mockito.Mockito.when; | ||
|
@@ -1278,6 +1279,79 @@ void updatePostById_WhenExists_isOk_DoctorRole() { | |
Assertions.assertThat(postService.updatePostById(userPrincipal, dto)).isTrue(); | ||
} | ||
|
||
@Test | ||
void updatePostById_WhenPostStatus_NotFount_ThrowException() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. |
||
Set<RolePermission> permissions = new HashSet<>(); | ||
permissions.add(RolePermission.DELETE_OWN_POST); | ||
|
||
RoleEntity roleEntity = new RoleEntity(); | ||
roleEntity.setId(3); | ||
roleEntity.setName("Doctor"); | ||
roleEntity.setPermissions(permissions); | ||
|
||
PostTypeIdOnlyDTO postTypeDTO = new PostTypeIdOnlyDTO(); | ||
postTypeDTO.setId(1); | ||
|
||
DirectionDTOForSavingPost directionDTO = new DirectionDTOForSavingPost(); | ||
directionDTO.setId(1); | ||
|
||
Set<@DirectionExists DirectionDTOForSavingPost> directions = new HashSet<>(); | ||
directions.add(directionDTO); | ||
|
||
OriginDTOForSavingPost originDTO = new OriginDTOForSavingPost(); | ||
originDTO.setId(1); | ||
|
||
Set<@OriginExists OriginDTOForSavingPost> origins = new HashSet<>(); | ||
origins.add(originDTO); | ||
|
||
UserPrincipal userPrincipal = UserPrincipal.builder() | ||
.id(38) | ||
.email("[email protected]") | ||
.password("$2a$10$ubeFvFhz0/P5js292OUaee9QxaBsI7cvoAmSp1inQ0MxI/gxazs8O") | ||
.role(roleEntity) | ||
.build(); | ||
|
||
UserEntity doctorUserEntity = UserEntity.builder() | ||
.id(38) | ||
.email("[email protected]") | ||
.password("$2a$10$ubeFvFhz0/P5js292OUaee9QxaBsI7cvoAmSp1inQ0MxI/gxazs8O") | ||
.role(roleEntity) | ||
.build(); | ||
|
||
PostSaveFromUserDTO dto = PostSaveFromUserDTO.builder() | ||
.id(1) | ||
.authorId(1) | ||
.title("title") | ||
.videoUrl("videoUrl") | ||
.previewImageUrl("previewImageUrl") | ||
.preview("preview") | ||
.content("content") | ||
.type(postTypeDTO) | ||
.directions(directions) | ||
.origins(origins) | ||
.postStatus(3) | ||
.build(); | ||
|
||
Integer id = 1; | ||
PostEntity postEntity = PostEntity | ||
.builder() | ||
.id(id) | ||
.author(doctorUserEntity) | ||
.build(); | ||
|
||
when(postMapper.updatePostEntityFromDTO(dto, postEntity)).thenReturn(postEntity); | ||
when(postRepository.findById(any(Integer.class))).thenReturn(Optional.of(postEntity)); | ||
Exception exception = assertThrows(ForbiddenPermissionsException.class, () -> | ||
postService.updatePostById(userPrincipal, dto) | ||
); | ||
String expectedMessage = "Forbidden permission"; | ||
assertEquals(expectedMessage, exception.getMessage()); | ||
verify(postRepository, never()) | ||
.save(any(PostEntity.class) | ||
); | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please remove empty line There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. |
||
} | ||
|
||
@Test | ||
void archivePostById_WhenExists_isOk_DoctorRole() { | ||
Set<RolePermission> permissions = new HashSet<>(); | ||
|
@@ -1723,4 +1797,30 @@ void setPublishedAtTest() { | |
Mockito.when(postRepository.findById(1)).thenReturn(Optional.of(postEntity)); | ||
assertTrue(postService.setPublishedAt(1, postPublishedAtDTO)); | ||
} | ||
|
||
@Test | ||
void setPublishedAt_WhenPost_NotFound_ThrowException() { | ||
Integer postId = 0; | ||
Timestamp publishedAt = Timestamp.valueOf( | ||
LocalDateTime.of( | ||
LocalDate.of( | ||
2002, Month.JANUARY, 14), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please move it on the same line with There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. |
||
LocalTime.MIN) | ||
); | ||
PostPublishedAtDTO postPublishedAtDTO = PostPublishedAtDTO | ||
.builder() | ||
.publishedAt(publishedAt) | ||
.build(); | ||
Exception exception = assertThrows(EntityNotFoundException.class, () -> | ||
postService.setPublishedAt(postId, postPublishedAtDTO) | ||
); | ||
String expectedMessage = "Post with this id=" + postId + " doesn't exist"; | ||
assertEquals(expectedMessage, exception.getMessage()); | ||
verify(postRepository, times(1)) | ||
.findById(any(Integer.class)); | ||
verify(postRepository, never()) | ||
.setPublishedAt(any(Integer.class), any(Timestamp.class)); | ||
verify(postRepository, never()) | ||
.save(any(PostEntity.class)); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please remove excessive empty lines
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed.