From 6fadf52cf4ec6d8f96686a3533248e5eed9659f4 Mon Sep 17 00:00:00 2001 From: YuriiSakharuk Date: Fri, 29 Jul 2022 13:02:23 +0300 Subject: [PATCH 1/4] Added tests for custom exceptions --- .../controller/AuthControllerTest.java | 92 ++++++++++++---- .../CustomUserDetailsServiceTest.java | 22 ++-- .../service/impl/PostServiceImplTest.java | 101 ++++++++++++++++++ .../service/impl/UserServiceImplTest.java | 17 +++ 4 files changed, 204 insertions(+), 28 deletions(-) diff --git a/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java b/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java index a2cb9159..035ed406 100644 --- a/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java +++ b/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java @@ -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 = "user@mail.com"; + 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 = "user@mail.com"; - String password = "user"; + LoginRequest loginRequest = createLoginRequest(EMAIL, PASSWORD); + Authentication authentication = authenticate(loginRequest); + UserEntity user = buildUserEntity(EMAIL, PASSWORD, true); + 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()); + } + + @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( 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) { diff --git a/src/test/java/com/softserveinc/dokazovi/security/CustomUserDetailsServiceTest.java b/src/test/java/com/softserveinc/dokazovi/security/CustomUserDetailsServiceTest.java index dd7ed3fa..9a15143d 100644 --- a/src/test/java/com/softserveinc/dokazovi/security/CustomUserDetailsServiceTest.java +++ b/src/test/java/com/softserveinc/dokazovi/security/CustomUserDetailsServiceTest.java @@ -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 = "test@test.com"; @@ -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)); + } } diff --git a/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java b/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java index c789cea8..9d7f7bab 100644 --- a/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java +++ b/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java @@ -61,7 +61,9 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.anyString; 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 +1280,79 @@ void updatePostById_WhenExists_isOk_DoctorRole() { Assertions.assertThat(postService.updatePostById(userPrincipal, dto)).isTrue(); } + @Test + void updatePostById_WhenPostStatus_NotFount_ThrowException() { + Set 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("doctor@mail.com") + .password("$2a$10$ubeFvFhz0/P5js292OUaee9QxaBsI7cvoAmSp1inQ0MxI/gxazs8O") + .role(roleEntity) + .build(); + + UserEntity doctorUserEntity = UserEntity.builder() + .id(38) + .email("doctor@mail.com") + .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) + ); + + } + @Test void archivePostById_WhenExists_isOk_DoctorRole() { Set permissions = new HashSet<>(); @@ -1723,4 +1798,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), + 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)); + } } diff --git a/src/test/java/com/softserveinc/dokazovi/service/impl/UserServiceImplTest.java b/src/test/java/com/softserveinc/dokazovi/service/impl/UserServiceImplTest.java index db972ef3..f691ba59 100644 --- a/src/test/java/com/softserveinc/dokazovi/service/impl/UserServiceImplTest.java +++ b/src/test/java/com/softserveinc/dokazovi/service/impl/UserServiceImplTest.java @@ -29,12 +29,14 @@ import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -359,6 +361,21 @@ void setEnableTrue() { .findById(any(Integer.class)); } + @Test + void setEnableTrue_WhenNotFound_ThrowException() { + UserEntity userEntity = UserEntity.builder() + .id(0) + .build(); + Exception exception = assertThrows(BadRequestException.class, () -> + userService.setEnableTrue(userEntity)); + String expectedMessage = "Something went wrong!!!"; + assertEquals(expectedMessage, exception.getMessage()); + verify(userRepository, times(1)) + .findById(any(Integer.class)); + verify(userRepository, never()) + .save(userEntity); + } + @Test void getVerificationToken() { String token = "950c9760-805e-449c-a966-2d0d5ebd86f4"; From 9cc9db4de52ade1dadb0532ac9fa08302d5d71a0 Mon Sep 17 00:00:00 2001 From: YuriiSakharuk Date: Mon, 1 Aug 2022 12:56:54 +0300 Subject: [PATCH 2/4] Fixed WhitespaceAround Error; removed unused imports. --- .../softserveinc/dokazovi/controller/AuthControllerTest.java | 4 ++-- .../dokazovi/service/impl/PostServiceImplTest.java | 3 +-- .../dokazovi/service/impl/UserServiceImplTest.java | 1 - 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java b/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java index 035ed406..49544c1f 100644 --- a/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java +++ b/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java @@ -119,7 +119,7 @@ void loginUser_WhenEnabledFalse_ThrowException() throws Exception { .findByEmail(anyString()); } - private LoginRequest createLoginRequest(String email, String password){ + private LoginRequest createLoginRequest(String email, String password) { LoginRequest loginRequest = new LoginRequest(); loginRequest.setEmail(email); loginRequest.setPassword(password); @@ -127,7 +127,7 @@ private LoginRequest createLoginRequest(String email, String password){ return loginRequest; } - private Authentication authenticate(LoginRequest loginRequest){ + private Authentication authenticate(LoginRequest loginRequest) { return authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( loginRequest.getEmail(), diff --git a/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java b/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java index 9d7f7bab..5bada425 100644 --- a/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java +++ b/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java @@ -61,7 +61,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anySet; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -1800,7 +1799,7 @@ void setPublishedAtTest() { } @Test - void setPublishedAt_WhenPost_NotFound_ThrowException(){ + void setPublishedAt_WhenPost_NotFound_ThrowException() { Integer postId = 0; Timestamp publishedAt = Timestamp.valueOf( LocalDateTime.of( diff --git a/src/test/java/com/softserveinc/dokazovi/service/impl/UserServiceImplTest.java b/src/test/java/com/softserveinc/dokazovi/service/impl/UserServiceImplTest.java index f691ba59..b7624ce0 100644 --- a/src/test/java/com/softserveinc/dokazovi/service/impl/UserServiceImplTest.java +++ b/src/test/java/com/softserveinc/dokazovi/service/impl/UserServiceImplTest.java @@ -29,7 +29,6 @@ import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; From d6596d55cc3f2704768c06c8622e7966871e9163 Mon Sep 17 00:00:00 2001 From: YuriiSakharuk Date: Fri, 12 Aug 2022 18:52:23 +0300 Subject: [PATCH 3/4] Fixed tests by comments --- .../dokazovi/controller/AuthControllerTest.java | 13 ++++++------- .../dokazovi/service/impl/PostServiceImplTest.java | 6 ++---- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java b/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java index 49544c1f..2d757973 100644 --- a/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java +++ b/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java @@ -40,8 +40,6 @@ @MockitoSettings(strictness = Strictness.LENIENT) class AuthControllerTest { - - private MockMvc mockMvc; @Mock private TokenProvider tokenProvider; @@ -80,17 +78,20 @@ void loginUser() throws Exception { UserEntity user = buildUserEntity(EMAIL, PASSWORD, true); when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) .thenReturn(authentication); - when(tokenProvider.createToken(any(Authentication.class))).thenReturn(TOKEN); + when(tokenProvider.createToken(authentication)).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)) + assertEquals(TOKEN, tokenProvider.createToken(authentication)); + verify(authenticationManager, times(1)) .authenticate(any(UsernamePasswordAuthenticationToken.class)); verify(userService, times(1)) .findByEmail(anyString()); + verify(tokenProvider, times(2)) + .createToken(authentication); } @Test @@ -128,11 +129,9 @@ private LoginRequest createLoginRequest(String email, String password) { } private Authentication authenticate(LoginRequest loginRequest) { - return authenticationManager.authenticate( - new UsernamePasswordAuthenticationToken( + return new UsernamePasswordAuthenticationToken( loginRequest.getEmail(), loginRequest.getPassword() - ) ); } diff --git a/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java b/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java index 5bada425..15395cb6 100644 --- a/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java +++ b/src/test/java/com/softserveinc/dokazovi/service/impl/PostServiceImplTest.java @@ -1280,7 +1280,7 @@ void updatePostById_WhenExists_isOk_DoctorRole() { } @Test - void updatePostById_WhenPostStatus_NotFount_ThrowException() { + void updatePostById_WhenPostStatus_NotFound_ThrowException() { Set permissions = new HashSet<>(); permissions.add(RolePermission.DELETE_OWN_POST); @@ -1349,7 +1349,6 @@ void updatePostById_WhenPostStatus_NotFount_ThrowException() { verify(postRepository, never()) .save(any(PostEntity.class) ); - } @Test @@ -1803,8 +1802,7 @@ void setPublishedAt_WhenPost_NotFound_ThrowException() { Integer postId = 0; Timestamp publishedAt = Timestamp.valueOf( LocalDateTime.of( - LocalDate.of( - 2002, Month.JANUARY, 14), + LocalDate.of(2002, Month.JANUARY, 14), LocalTime.MIN) ); PostPublishedAtDTO postPublishedAtDTO = PostPublishedAtDTO From 55c24406eb63db41923f82137e7bcd0f73f98bd4 Mon Sep 17 00:00:00 2001 From: YuriiSakharuk Date: Wed, 17 Aug 2022 18:26:48 +0300 Subject: [PATCH 4/4] Fixed assertion of Token in loginUser-test --- .../dokazovi/controller/AuthControllerTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java b/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java index 2d757973..518e2f1b 100644 --- a/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java +++ b/src/test/java/com/softserveinc/dokazovi/controller/AuthControllerTest.java @@ -84,13 +84,13 @@ void loginUser() throws Exception { .content(asJsonString(loginRequest)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - assertEquals(TOKEN, tokenProvider.createToken(authentication)); + .andExpect(status().isOk()) + .andExpect(mvcResult -> mvcResult.getResponse().getContentAsString().equals(TOKEN)); verify(authenticationManager, times(1)) .authenticate(any(UsernamePasswordAuthenticationToken.class)); verify(userService, times(1)) .findByEmail(anyString()); - verify(tokenProvider, times(2)) + verify(tokenProvider, times(1)) .createToken(authentication); }