diff --git a/src/main/java/com/sopromadze/blogapi/service/impl/UserServiceImpl.java b/src/main/java/com/sopromadze/blogapi/service/impl/UserServiceImpl.java index d740f27b..51089ad9 100644 --- a/src/main/java/com/sopromadze/blogapi/service/impl/UserServiceImpl.java +++ b/src/main/java/com/sopromadze/blogapi/service/impl/UserServiceImpl.java @@ -120,7 +120,7 @@ public User updateUser(User newUser, String username, UserPrincipal currentUser) public ApiResponse deleteUser(String username, UserPrincipal currentUser) { User user = userRepository.findByUsername(username) .orElseThrow(() -> new ResourceNotFoundException("User", "id", username)); - if (!user.getId().equals(currentUser.getId()) || !currentUser.getAuthorities() + if (!user.getId().equals(currentUser.getId()) && !currentUser.getAuthorities() .contains(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString()))) { ApiResponse apiResponse = new ApiResponse(Boolean.FALSE, "You don't have permission to delete profile of: " + username); throw new AccessDeniedException(apiResponse); diff --git a/src/test/java/com/sopromadze/blogapi/controller/AuthControllerTests.java b/src/test/java/com/sopromadze/blogapi/controller/AuthControllerTests.java new file mode 100644 index 00000000..71772be4 --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/controller/AuthControllerTests.java @@ -0,0 +1,160 @@ +package com.sopromadze.blogapi.controller; + +import com.sopromadze.blogapi.exception.AppException; +import com.sopromadze.blogapi.exception.BlogapiException; +import com.sopromadze.blogapi.model.role.Role; +import com.sopromadze.blogapi.model.role.RoleName; +import com.sopromadze.blogapi.model.user.User; +import com.sopromadze.blogapi.payload.ApiResponse; +import com.sopromadze.blogapi.payload.SignUpRequest; +import com.sopromadze.blogapi.repository.RoleRepository; +import com.sopromadze.blogapi.repository.UserRepository; +import com.sopromadze.blogapi.security.JwtTokenProvider; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.util.Objects; +import java.util.Optional; + +@RunWith(SpringRunner.class) +public class AuthControllerTests { + + @Mock + private AuthenticationManager authenticationManager; + + @Mock + private UserRepository userRepository; + + @Mock + private RoleRepository roleRepository; + + @Mock + private PasswordEncoder passwordEncoder; + + @Mock + private JwtTokenProvider jwtTokenProvider; + + @InjectMocks + private AuthController authController; + + private SignUpRequest signUpRequest; + + @Before + public void setup() { + signUpRequest = new SignUpRequest(); + signUpRequest.setUsername("john.doe"); + signUpRequest.setEmail("john.doe@example.com"); + signUpRequest.setFirstName("John"); + signUpRequest.setLastName("Doe"); + signUpRequest.setPassword("Password123!"); + } + + @Test(expected = BlogapiException.class) + public void registerUser_whenUsernameTaken_thenThrowException() { + try { + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(Boolean.TRUE); + + authController.registerUser(signUpRequest); + } catch (BlogapiException e) { + Assert.assertEquals(400, e.getStatus().value()); + Assert.assertEquals("Username is already taken", e.getMessage()); + throw e; + } + } + + @Test(expected = BlogapiException.class) + public void registerUser_whenEmailTaken_thenThrowException() { + try { + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(userRepository.existsByEmail(Mockito.anyString())).thenReturn(Boolean.TRUE); + + authController.registerUser(signUpRequest); + } catch (BlogapiException e) { + Assert.assertEquals(400, e.getStatus().value()); + Assert.assertEquals("Email is already taken", e.getMessage()); + throw e; + } + } + + @Test(expected = AppException.class) + public void registerUser_whenNoUsersAndUserRoleNotFound_thenThrowException() { + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(userRepository.existsByEmail(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(passwordEncoder.encode(Mockito.any())).thenReturn("Encoded"); + Mockito.when(userRepository.count()).thenReturn(0L); + Mockito.when(roleRepository.findByName(Mockito.any())).thenReturn(Optional.empty()); + + authController.registerUser(signUpRequest); + } + + @Test(expected = AppException.class) + public void registerUser_whenNoUsersAndAdminRoleNotFound_thenThrowException() { + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(userRepository.existsByEmail(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(passwordEncoder.encode(Mockito.any())).thenReturn("Encoded"); + Mockito.when(userRepository.count()).thenReturn(0L); + Mockito.when(roleRepository.findByName(RoleName.ROLE_USER)).thenReturn(Optional.of(new Role())); + Mockito.when(roleRepository.findByName(RoleName.ROLE_ADMIN)).thenReturn(Optional.empty()); + + authController.registerUser(signUpRequest); + } + + @Test(expected = AppException.class) + public void registerUser_whenUsersAddedAndUserRoleNotFound_thenThrowException() { + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(userRepository.existsByEmail(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(passwordEncoder.encode(Mockito.any())).thenReturn("Encoded"); + Mockito.when(userRepository.count()).thenReturn(1L); + Mockito.when(roleRepository.findByName(RoleName.ROLE_USER)).thenReturn(Optional.empty()); + + authController.registerUser(signUpRequest); + } + + @Test + public void registerUser_whenUserRegistered_thenReturnSuccessResponse() { + User user = new User(); + user.setId(1L); + MockHttpServletRequest request = new MockHttpServletRequest(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(userRepository.existsByEmail(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(passwordEncoder.encode(Mockito.any())).thenReturn("Encoded"); + Mockito.when(userRepository.count()).thenReturn(1L); + Mockito.when(roleRepository.findByName(RoleName.ROLE_USER)).thenReturn(Optional.of(new Role())); + Mockito.when(userRepository.save(Mockito.any())).thenReturn(user); + + ResponseEntity response = authController.registerUser(signUpRequest); + Assert.assertTrue(Objects.requireNonNull(response.getBody()).getSuccess()); + } + + @Test + public void registerUser_whenNoUsersYetAndUserRegistered_thenReturnSuccessResponse() { + User user = new User(); + user.setId(1L); + MockHttpServletRequest request = new MockHttpServletRequest(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(userRepository.existsByEmail(Mockito.anyString())).thenReturn(Boolean.FALSE); + Mockito.when(passwordEncoder.encode(Mockito.any())).thenReturn("Encoded"); + Mockito.when(userRepository.count()).thenReturn(0L); + Mockito.when(roleRepository.findByName(Mockito.any())).thenReturn(Optional.of(new Role())); + Mockito.when(userRepository.save(Mockito.any())).thenReturn(user); + + ResponseEntity response = authController.registerUser(signUpRequest); + Assert.assertTrue(Objects.requireNonNull(response.getBody()).getSuccess()); + } +} diff --git a/src/test/java/com/sopromadze/blogapi/controller/CommentControllerTests.java b/src/test/java/com/sopromadze/blogapi/controller/CommentControllerTests.java new file mode 100644 index 00000000..495e579d --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/controller/CommentControllerTests.java @@ -0,0 +1,61 @@ +package com.sopromadze.blogapi.controller; + +import com.sopromadze.blogapi.payload.ApiResponse; +import com.sopromadze.blogapi.security.UserPrincipal; +import com.sopromadze.blogapi.service.CommentService; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.Collection; + +@RunWith(SpringRunner.class) +public class CommentControllerTests { + + @Mock + private CommentService commentService; + + @InjectMocks + private CommentController commentController; + + private UserPrincipal userPrincipal; + + @Before + public void setup() { + Collection authorities = new ArrayList<>(); + userPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + } + + @Test + public void deleteComment_whenCommentServiceUnsuccessful_thenSend400Status() { + ApiResponse serviceResponse = new ApiResponse(); + serviceResponse.setSuccess(false); + + Mockito.when(commentService.deleteComment(Mockito.anyLong(), Mockito.anyLong(), Mockito.any())) + .thenReturn(serviceResponse); + + ResponseEntity response = commentController.deleteComment(1L,1L, userPrincipal); + Assert.assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void deleteComment_whenCommentServiceSuccessful_thenSend200Status() { + ApiResponse serviceResponse = new ApiResponse(); + serviceResponse.setSuccess(true); + + Mockito.when(commentService.deleteComment(Mockito.anyLong(), Mockito.anyLong(), Mockito.any())) + .thenReturn(serviceResponse); + + ResponseEntity response = commentController.deleteComment(1L,1L, userPrincipal); + Assert.assertEquals(200, response.getStatusCodeValue()); + } +} diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/AlbumServiceImplTests.java b/src/test/java/com/sopromadze/blogapi/service/impl/AlbumServiceImplTests.java new file mode 100644 index 00000000..7d81e76d --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/service/impl/AlbumServiceImplTests.java @@ -0,0 +1,176 @@ +package com.sopromadze.blogapi.service.impl; + +import com.sopromadze.blogapi.exception.BlogapiException; +import com.sopromadze.blogapi.exception.ResourceNotFoundException; +import com.sopromadze.blogapi.model.Album; +import com.sopromadze.blogapi.model.user.User; +import com.sopromadze.blogapi.payload.AlbumResponse; +import com.sopromadze.blogapi.payload.PagedResponse; +import com.sopromadze.blogapi.payload.request.AlbumRequest; +import com.sopromadze.blogapi.repository.AlbumRepository; +import com.sopromadze.blogapi.repository.UserRepository; +import com.sopromadze.blogapi.security.UserPrincipal; +import com.sopromadze.blogapi.utils.AppUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.modelmapper.ModelMapper; +import org.springframework.data.domain.*; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.*; + +@RunWith(SpringRunner.class) +public class AlbumServiceImplTests { + + @Mock + private AppUtils appUtils; + + @Mock + private AlbumRepository albumRepository; + + @Mock + private UserRepository userRepository; + + @Mock + private ModelMapper modelMapper; + + @Mock + private Pageable pageable; + + @InjectMocks + private AlbumServiceImpl albumService; + + @Test + public void getAllAlbums_whenNoElementsReturned_thenEmptyListInResponse() { + Mockito.when(albumRepository.findAll(Mockito.any(Pageable.class))).thenReturn(Page.empty()); + + PagedResponse testResponse = albumService.getAllAlbums(1, 2); + + Assert.assertEquals(0, testResponse.getContent().size()); + Assert.assertEquals(Collections.emptyList(), testResponse.getContent()); + } + + @Test(expected = ResourceNotFoundException.class) + public void getAlbum_whenNoResourceFound_thenThrowException() { + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + albumService.getAlbum(1L); + } + + @Test + public void getAlbum_whenAlbumFound_thenReturn200AndAlbum() { + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new Album())); + ResponseEntity response = albumService.getAlbum(1L); + Assert.assertEquals(200, response.getStatusCodeValue()); + Assert.assertNotNull(response.getBody()); + } + + @Test(expected = ResourceNotFoundException.class) + public void updateAlbum_whenNoResourceFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + albumService.updateAlbum(1L, new AlbumRequest(), fakeUserPrincipal); + } + + @Test(expected = BlogapiException.class) + public void updateAlbum_whenUserUnauthorized_thenThrowException() { + try { + Album testAlbum = new Album(); + AlbumRequest fakeAlbumRequest = new AlbumRequest(); + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + fakeUser.setId(1L); + User albumFakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + albumFakeUser.setId(2L); + testAlbum.setUser(albumFakeUser); + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testAlbum)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(fakeUser); + + albumService.updateAlbum(1L, fakeAlbumRequest, fakeUserPrincipal); + } catch (BlogapiException e) { + Assert.assertEquals(401, e.getStatus().value()); + Assert.assertNotNull(e.getMessage()); + throw e; + } + } + + @Test + public void updateAlbum_whenAlbumFoundAndUserAuthorized_thenReturnAlbumResponse() { + Album testAlbum = new Album(); + AlbumRequest fakeAlbumRequest = new AlbumRequest(); + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + fakeUser.setId(1L); + testAlbum.setUser(fakeUser); + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testAlbum)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(fakeUser); + + ResponseEntity response = albumService.updateAlbum(1L, fakeAlbumRequest, fakeUserPrincipal); + Assert.assertEquals(200, response.getStatusCodeValue()); + Assert.assertNotNull(response.getBody()); + } + + @Test(expected = ResourceNotFoundException.class) + public void deleteAlbum_whenNoResourceFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + albumService.deleteAlbum(1L, fakeUserPrincipal); + } + + @Test(expected = BlogapiException.class) + public void deleteAlbum_whenUserUnauthorized_thenThrowException() { + try { + Album testAlbum = new Album(); + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + fakeUser.setId(1L); + User albumFakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + albumFakeUser.setId(2L); + testAlbum.setUser(albumFakeUser); + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testAlbum)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(fakeUser); + + albumService.deleteAlbum(1L, fakeUserPrincipal); + } catch (BlogapiException e) { + Assert.assertEquals(401, e.getStatus().value()); + Assert.assertNotNull(e.getMessage()); + throw e; + } + } + + @Test + public void deleteAlbum_whenAlbumDeleted_theReturnSuccessResponse() { + Album testAlbum = new Album(); + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + fakeUser.setId(1L); + testAlbum.setUser(fakeUser); + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testAlbum)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(fakeUser); + + ResponseEntity response = albumService.deleteAlbum(1L, fakeUserPrincipal); + Assert.assertEquals(200, response.getStatusCodeValue()); + Assert.assertNotNull(response.getBody()); + } +} diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/CategoryServiceImplTests.java b/src/test/java/com/sopromadze/blogapi/service/impl/CategoryServiceImplTests.java new file mode 100644 index 00000000..a8a192f2 --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/service/impl/CategoryServiceImplTests.java @@ -0,0 +1,195 @@ +package com.sopromadze.blogapi.service.impl; + +import com.sopromadze.blogapi.exception.ResourceNotFoundException; +import com.sopromadze.blogapi.exception.UnauthorizedException; +import com.sopromadze.blogapi.model.Category; +import com.sopromadze.blogapi.model.user.User; +import com.sopromadze.blogapi.payload.ApiResponse; +import com.sopromadze.blogapi.payload.PagedResponse; +import com.sopromadze.blogapi.repository.CategoryRepository; +import com.sopromadze.blogapi.security.UserPrincipal; +import com.sopromadze.blogapi.utils.AppUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.*; + +@RunWith(SpringRunner.class) +public class CategoryServiceImplTests { + + @Mock + private CategoryRepository categoryRepository; + + @Mock + private AppUtils appUtils; + + @Mock + private Pageable pageable; + + @InjectMocks + private CategoryServiceImpl categoryService; + + @Test + public void getAllCategories_whenNoElementsFound_thenReturnEmptyList() { + Mockito.when(categoryRepository.findAll(Mockito.any(Pageable.class))).thenReturn(Page.empty()); + + PagedResponse response = categoryService.getAllCategories(1, 2); + + Assert.assertEquals(0, response.getContent().size()); + Assert.assertEquals(Collections.emptyList(), response.getContent()); + } + + @Test + public void getAllCategories_whenElementsFound_returnContent() { + // Mock the Page interface using Mockito.mock + Page page = Mockito.mock(Page.class); + + // Configure the behavior of the mock + Mockito.when(page.getTotalPages()).thenReturn(1); + Mockito.when(page.getTotalElements()).thenReturn(1L); + Mockito.when(page.getNumber()).thenReturn(0); + Mockito.when(page.getSize()).thenReturn(1); + Mockito.when(page.getNumberOfElements()).thenReturn(1); + Mockito.when(page.getContent()).thenReturn(createCategoryList()); + + // Mock the repository method to return the mock Page + Mockito.when(categoryRepository.findAll(Mockito.any(Pageable.class))).thenReturn(page); + + // Call the service method + PagedResponse response = categoryService.getAllCategories(1, 2); + + // Assert the results + Assert.assertNotNull(response.getContent()); + Assert.assertEquals(1, response.getContent().size()); + } + + @Test(expected = ResourceNotFoundException.class) + public void getCategory_whenNoResourceFound_thenThrowException() { + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + categoryService.getCategory(1L); + } + + @Test + public void getCategory_whenCategoryFound_thenReturnCategory() { + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new Category())); + ResponseEntity response = categoryService.getCategory(1L); + Assert.assertEquals(200, response.getStatusCodeValue()); + Assert.assertNotNull(response.getBody()); + } + + @Test(expected = ResourceNotFoundException.class) + public void updateCategory_whenNoResourceFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + categoryService.updateCategory(1L, new Category(), fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void updateCategory_whenUserUnauthorized_thenThrowException() { + try { + Category categoryParam = new Category(); + Category returnCategory = new Category(); + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + fakeUser.setId(1L); + User categoryFakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + returnCategory.setCreatedBy(2L); + categoryParam.setCreatedBy(1L); + + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(returnCategory)); + + categoryService.updateCategory(1L, categoryParam, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertNotNull(e.getMessage()); + throw e; + } + } + + @Test + public void updateCategory_whenCategoryUpdated_thenReturnSuccessResponse() { + Category categoryParam = new Category(); + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + fakeUser.setId(1L); + User categoryFakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + categoryParam.setCreatedBy(1L); + + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(categoryParam)); + + ResponseEntity response = categoryService.updateCategory(1L, categoryParam, fakeUserPrincipal); + Assert.assertEquals(200, response.getStatusCodeValue()); + } + + @Test(expected = ResourceNotFoundException.class) + public void deleteCategory_whenNoResourceFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + categoryService.deleteCategory(1L, fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void deleteCategory_whenUserUnauthorized_thenThrowException() { + try { + Category testCategory = new Category(); + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + fakeUser.setId(1L); + User categoryFakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + testCategory.setCreatedBy(2L); + + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testCategory)); + categoryService.deleteCategory(1L, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertNotNull(e.getMessage()); + throw e; + } + } + + @Test + public void deleteCategory_whenCategoryDeleted_thenReturnSuccessResponse() { + Category categoryParam = new Category(); + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + fakeUser.setId(1L); + User categoryFakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + categoryParam.setCreatedBy(1L); + + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(categoryParam)); + + ResponseEntity response = categoryService.deleteCategory(1L, fakeUserPrincipal); + Assert.assertEquals(200, response.getStatusCodeValue()); + Assert.assertNotNull(response.getBody()); + } + + // Helper method to create a list of categories + private List createCategoryList() { + List list = new ArrayList<>(); + Category category = new Category(); + list.add(category); + return list; + } +} diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/CommentServiceImplTests.java b/src/test/java/com/sopromadze/blogapi/service/impl/CommentServiceImplTests.java new file mode 100644 index 00000000..f1ad3f4d --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/service/impl/CommentServiceImplTests.java @@ -0,0 +1,306 @@ +package com.sopromadze.blogapi.service.impl; + +import com.sopromadze.blogapi.exception.BlogapiException; +import com.sopromadze.blogapi.exception.ResourceNotFoundException; +import com.sopromadze.blogapi.model.Comment; +import com.sopromadze.blogapi.model.Post; +import com.sopromadze.blogapi.model.user.User; +import com.sopromadze.blogapi.payload.ApiResponse; +import com.sopromadze.blogapi.payload.CommentRequest; +import com.sopromadze.blogapi.repository.CommentRepository; +import com.sopromadze.blogapi.repository.PostRepository; +import com.sopromadze.blogapi.repository.UserRepository; +import com.sopromadze.blogapi.security.UserPrincipal; +import com.sopromadze.blogapi.utils.AppUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Optional; + +@RunWith(SpringRunner.class) +public class CommentServiceImplTests { + + @Mock + private AppUtils appUtils; + + @Mock + private CommentRepository commentRepository; + + @Mock + private PostRepository postRepository; + + @Mock + private UserRepository userRepository; + + @InjectMocks + private CommentServiceImpl commentService; + + @Test(expected = ResourceNotFoundException.class) + public void addComment_whenNoResourceFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + commentService.addComment(new CommentRequest(), 1L, fakeUserPrincipal); + } + + @Test + public void addComment_whenPostFound_thenSaveComment() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Post testPost = new Post(); + User fakeUser = new User("John", "Doe", "john.doe", "john.doe@example.com", "password123"); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPost)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(fakeUser); + + commentService.addComment(new CommentRequest(), 1L, fakeUserPrincipal); + } + + @Test(expected = ResourceNotFoundException.class) + public void getComment_whenPostNotFound_thenThrowException() { + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + commentService.getComment(1L, 1L); + } + + @Test(expected = ResourceNotFoundException.class) + public void getComment_whenCommentNotFound_thenThrowException() { + Post fakePost = new Post(); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(fakePost)); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + commentService.getComment(1L, 1L); + } + + @Test + public void getComment_whenCommentFoundAndPostIdMatches_theReturnComment() { + Post testPost = new Post(); + testPost.setId(1L); + Comment testComment = new Comment(); + testComment.setId(1L); + testComment.setPost(testPost); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPost)); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testComment)); + + commentService.getComment(1L, 1L); + } + + @Test(expected = BlogapiException.class) + public void getComment_whenPostIdNotMatch_thenThrowException() { + try { + Post testPost = new Post(); + testPost.setId(1L); + Post fakePost = new Post(); + fakePost.setId(2L); + Comment testComment = new Comment(); + testComment.setId(1L); + testComment.setPost(fakePost); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPost)); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testComment)); + + commentService.getComment(1L, 1L); + } catch (BlogapiException e) { + Assert.assertEquals(400, e.getStatus().value()); + Assert.assertNotNull(e.getMessage()); + throw e; + } + } + + @Test(expected = ResourceNotFoundException.class) + public void updateComment_whenPostNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + commentService.updateComment(1L, 1L, new CommentRequest(), fakeUserPrincipal); + } + + @Test(expected = ResourceNotFoundException.class) + public void updateComment_whenCommentNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new Post())); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + commentService.updateComment(1L, 1L, new CommentRequest(), fakeUserPrincipal); + } + + @Test(expected = BlogapiException.class) + public void updateComment_whenPostIdNotMatch_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Post testPost = new Post(); + testPost.setId(1L); + Post fakePost = new Post(); + fakePost.setId(2L); + Comment testComment = new Comment(); + testComment.setId(1L); + testComment.setPost(fakePost); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPost)); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testComment)); + + commentService.updateComment(1L, 1L, new CommentRequest(), fakeUserPrincipal); + } catch (BlogapiException e) { + Assert.assertEquals(400, e.getStatus().value()); + Assert.assertNotNull(e.getMessage()); + throw e; + } + } + + @Test + public void updateComment_whenCommentFoundAndUserAuthorized_thenSaveComment() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Post testPost = new Post(); + testPost.setId(1L); + User testUser = new User(); + testUser.setId(1L); + Comment testComment = new Comment(); + testComment.setId(1L); + testComment.setPost(testPost); + testComment.setUser(testUser); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPost)); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testComment)); + + commentService.updateComment(1L, 1L, new CommentRequest(), fakeUserPrincipal); + } + + @Test(expected = BlogapiException.class) + public void updateComment_whenUserUnauthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Post testPost = new Post(); + testPost.setId(1L); + User testUser = new User(); + testUser.setId(2L); + Comment testComment = new Comment(); + testComment.setId(1L); + testComment.setPost(testPost); + testComment.setUser(testUser); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPost)); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testComment)); + + commentService.updateComment(1L, 1L, new CommentRequest(), fakeUserPrincipal); + } catch (BlogapiException e) { + Assert.assertEquals(401, e.getStatus().value()); + Assert.assertNotNull(e.getMessage()); + throw e; + } + } + + @Test(expected = ResourceNotFoundException.class) + public void deleteComment_whenPostNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + commentService.deleteComment(1L, 1L, fakeUserPrincipal); + } + + @Test(expected = ResourceNotFoundException.class) + public void deleteComment_whenCommentNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new Post())); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + commentService.deleteComment(1L, 1L, fakeUserPrincipal); + } + + @Test + public void deleteComment_whenCommentNotOnPost_thenSendResponseWithInformation() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Post testPost = new Post(); + testPost.setId(1L); + Post fakePost = new Post(); + fakePost.setId(2L); + Comment testComment = new Comment(); + testComment.setId(1L); + testComment.setPost(fakePost); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPost)); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testComment)); + + ApiResponse response = commentService.deleteComment(1L, 1L, fakeUserPrincipal); + Assert.assertEquals(false, response.getSuccess()); + Assert.assertNotNull(response.getMessage()); + } + + @Test + public void deleteComment_whenUserAuthorized_thenDeleteComment() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Post testPost = new Post(); + testPost.setId(1L); + User testUser = new User(); + testUser.setId(1L); + Comment testComment = new Comment(); + testComment.setId(1L); + testComment.setPost(testPost); + testComment.setUser(testUser); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPost)); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testComment)); + + ApiResponse response = commentService.deleteComment(1L, 1L, fakeUserPrincipal); + Assert.assertEquals(true, response.getSuccess()); + Assert.assertNotNull(response.getMessage()); + } + + @Test(expected = BlogapiException.class) + public void deleteComment_whenUserNotAuthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Post testPost = new Post(); + testPost.setId(1L); + User testUser = new User(); + testUser.setId(2L); + Comment testComment = new Comment(); + testComment.setId(1L); + testComment.setPost(testPost); + testComment.setUser(testUser); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testPost)); + Mockito.when(commentRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(testComment)); + + commentService.deleteComment(1L, 1L, fakeUserPrincipal); + } catch (BlogapiException e) { + Assert.assertEquals(401, e.getStatus().value()); + Assert.assertNotNull(e.getMessage()); + throw e; + } + } +} diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/CustomUserDetailsServiceImplTests.java b/src/test/java/com/sopromadze/blogapi/service/impl/CustomUserDetailsServiceImplTests.java new file mode 100644 index 00000000..c59448a0 --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/service/impl/CustomUserDetailsServiceImplTests.java @@ -0,0 +1,37 @@ +package com.sopromadze.blogapi.service.impl; + +import com.sopromadze.blogapi.repository.UserRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Optional; + +@RunWith(SpringRunner.class) +public class CustomUserDetailsServiceImplTests { + + @Mock + private UserRepository userRepository; + + @InjectMocks + CustomUserDetailsServiceImpl customUserDetailsService; + + @Test(expected = UsernameNotFoundException.class) + public void loadUserByUsername_whenUserNotFound_thenThrowException() { + Mockito.when(userRepository.findByUsernameOrEmail(Mockito.anyString(), Mockito.anyString())) + .thenReturn(Optional.empty()); + + customUserDetailsService.loadUserByUsername("john.doe@example.com"); + } + + @Test(expected = UsernameNotFoundException.class) + public void loadUserById_whenUserNotFound_thenThrowException() { + Mockito.when(userRepository.findById(1L)).thenReturn(Optional.empty()); + + customUserDetailsService.loadUserById(1L); + } +} diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/PhotoServiceImplTests.java b/src/test/java/com/sopromadze/blogapi/service/impl/PhotoServiceImplTests.java new file mode 100644 index 00000000..31d3441d --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/service/impl/PhotoServiceImplTests.java @@ -0,0 +1,316 @@ +package com.sopromadze.blogapi.service.impl; + +import com.sopromadze.blogapi.exception.ResourceNotFoundException; +import com.sopromadze.blogapi.exception.UnauthorizedException; +import com.sopromadze.blogapi.model.Album; +import com.sopromadze.blogapi.model.Photo; +import com.sopromadze.blogapi.model.user.User; +import com.sopromadze.blogapi.payload.ApiResponse; +import com.sopromadze.blogapi.payload.PagedResponse; +import com.sopromadze.blogapi.payload.PhotoRequest; +import com.sopromadze.blogapi.payload.PhotoResponse; +import com.sopromadze.blogapi.repository.AlbumRepository; +import com.sopromadze.blogapi.repository.PhotoRepository; +import com.sopromadze.blogapi.security.UserPrincipal; +import com.sopromadze.blogapi.utils.AppUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.*; + +@RunWith(SpringRunner.class) +public class PhotoServiceImplTests { + + @Mock + private PageRequest pageRequest; + + @Mock + AppUtils appUtils; + + @Mock + private PhotoRepository photoRepository; + + @Mock + private AlbumRepository albumRepository; + + @InjectMocks + private PhotoServiceImpl photoService; + + @Test + public void getAllPhotos_whenPhotosEmpty_thenReturnEmptyList() { + Mockito.when(photoRepository.findAll(Mockito.any(Pageable.class))).thenReturn(Page.empty()); + + PagedResponse response = photoService.getAllPhotos(1, 2); + + Assert.assertEquals(0, response.getContent().size()); + Assert.assertEquals(Collections.emptyList(), response.getContent()); + } + + @Test + public void getAllPhotos_whenPhotosFound_thenReturnPhotoResponse() { + Page testPage = Mockito.mock(Page.class); + Mockito.when(testPage.getTotalPages()).thenReturn(1); + Mockito.when(testPage.getTotalElements()).thenReturn(1L); + Mockito.when(testPage.getNumber()).thenReturn(0); + Mockito.when(testPage.getSize()).thenReturn(1); + Mockito.when(testPage.getNumberOfElements()).thenReturn(1); + Mockito.when(testPage.getContent()).thenReturn(createPhotoList()); + + Mockito.when(photoRepository.findAll(Mockito.any(Pageable.class))).thenReturn(testPage); + + PagedResponse response = photoService.getAllPhotos(1, 2); + + Assert.assertNotNull(response); + Assert.assertEquals(1, response.getContent().size()); + } + + @Test(expected = ResourceNotFoundException.class) + public void getPhoto_whenPhotoNotFound_thenThrowException() { + Mockito.when(photoRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + photoService.getPhoto(1L); + } + + @Test + public void getPhoto_whenPhotoFound_thenReturnPhotoResponse() { + Photo photo = new Photo(); + Album album = new Album(); + album.setId(1L); + photo.setAlbum(album); + + Mockito.when(photoRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(photo)); + + photoService.getPhoto(1L); + } + + @Test(expected = ResourceNotFoundException.class) + public void updatePhoto_whenAlbumNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + photoService.updatePhoto(1L, new PhotoRequest(), fakeUserPrincipal); + } + + @Test(expected = ResourceNotFoundException.class) + public void updatePhoto_whenNoPhotoFound_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Album album = new Album(); + PhotoRequest request = new PhotoRequest(); + request.setAlbumId(1L); + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(album)); + Mockito.when(photoRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + photoService.updatePhoto(1L, request, fakeUserPrincipal); + } catch (ResourceNotFoundException e) { + Assert.assertEquals("Photo", e.getResourceName()); + throw e; + } + } + + @Test + public void updatePhoto_whenUserAuthorized_thenReturnPhotoResponse() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User(); + fakeUser.setId(1L); + Album album = new Album(); + album.setId(1L); + album.setUser(fakeUser); + Photo photo = new Photo(); + photo.setAlbum(album); + PhotoRequest request = new PhotoRequest(); + request.setAlbumId(1L); + + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(album)); + Mockito.when(photoRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(photo)); + Mockito.when(photoRepository.save(Mockito.any())).thenReturn(photo); + + photoService.updatePhoto(1L, request, fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void updatePhoto_whenUserNotAuthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User(); + fakeUser.setId(2L); + Album album = new Album(); + album.setId(1L); + album.setUser(fakeUser); + Photo photo = new Photo(); + photo.setAlbum(album); + PhotoRequest request = new PhotoRequest(); + request.setAlbumId(1L); + + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(album)); + Mockito.when(photoRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(photo)); + + photoService.updatePhoto(1L, request, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertEquals(false, e.getApiResponse().getSuccess()); + throw e; + } + } + + @Test(expected = ResourceNotFoundException.class) + public void addPhoto_whenAlbumNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + PhotoRequest request = new PhotoRequest(); + request.setAlbumId(1L); + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + photoService.addPhoto(request, fakeUserPrincipal); + } + + @Test + public void addPhoto_whenUserMatches_thenReturnPhotoResponse() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User(); + fakeUser.setId(1L); + Album album = new Album(); + album.setId(1L); + album.setUser(fakeUser); + Photo photo = new Photo(); + photo.setAlbum(album); + PhotoRequest request = new PhotoRequest(); + request.setAlbumId(1L); + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(album)); + Mockito.when(photoRepository.save(Mockito.any())).thenReturn(photo); + + photoService.addPhoto(request, fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void addPhoto_whenUserNotAuthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User(); + fakeUser.setId(2L); + Album album = new Album(); + album.setId(1L); + album.setUser(fakeUser); + Photo photo = new Photo(); + photo.setAlbum(album); + PhotoRequest request = new PhotoRequest(); + request.setAlbumId(1L); + + Mockito.when(albumRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(album)); + + photoService.addPhoto(request, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertEquals(false, e.getApiResponse().getSuccess()); + throw e; + } + } + + @Test(expected = ResourceNotFoundException.class) + public void deletePhoto_whenPhotoNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(photoRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + photoService.deletePhoto(1L, fakeUserPrincipal); + } + + @Test + public void deletePhoto_whenUserMatches_thenDeletePhoto() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User(); + fakeUser.setId(1L); + Album album = new Album(); + album.setId(1L); + album.setUser(fakeUser); + Photo photo = new Photo(); + photo.setAlbum(album); + PhotoRequest request = new PhotoRequest(); + request.setAlbumId(1L); + + Mockito.when(photoRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(photo)); + + ApiResponse response = photoService.deletePhoto(1L, fakeUserPrincipal); + Assert.assertTrue(response.getSuccess()); + } + + @Test(expected = UnauthorizedException.class) + public void deletePhoto_whenUserNotAuthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User fakeUser = new User(); + fakeUser.setId(2L); + Album album = new Album(); + album.setId(1L); + album.setUser(fakeUser); + Photo photo = new Photo(); + photo.setAlbum(album); + PhotoRequest request = new PhotoRequest(); + request.setAlbumId(1L); + + Mockito.when(photoRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(photo)); + photoService.deletePhoto(1L, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertFalse(e.getApiResponse().getSuccess()); + throw e; + } + } + + @Test + public void getAllPhotosByAlbum_whenAlbumRequested_thenReturnPhotosInAlbum() { + Page testPage = Mockito.mock(Page.class); + Mockito.when(testPage.getTotalPages()).thenReturn(1); + Mockito.when(testPage.getTotalElements()).thenReturn(1L); + Mockito.when(testPage.getNumber()).thenReturn(0); + Mockito.when(testPage.getSize()).thenReturn(1); + Mockito.when(testPage.getNumberOfElements()).thenReturn(1); + Mockito.when(testPage.getContent()).thenReturn(createPhotoList()); + + Mockito.when(photoRepository.findByAlbumId(Mockito.anyLong(), Mockito.any(Pageable.class))).thenReturn(testPage); + + PagedResponse response = photoService.getAllPhotosByAlbum(1L, 1, 2); + + Assert.assertNotNull(response); + } + + private List createPhotoList() { + List list = new ArrayList<>(); + Photo photo = new Photo(); + Album fakeAlbum = new Album(); + fakeAlbum.setId(1L); + photo.setAlbum(fakeAlbum); + list.add(photo); + return list; + } +} diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/PostServiceImplTests.java b/src/test/java/com/sopromadze/blogapi/service/impl/PostServiceImplTests.java new file mode 100644 index 00000000..3d49d49c --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/service/impl/PostServiceImplTests.java @@ -0,0 +1,385 @@ +package com.sopromadze.blogapi.service.impl; + +import com.sopromadze.blogapi.exception.ResourceNotFoundException; +import com.sopromadze.blogapi.exception.UnauthorizedException; +import com.sopromadze.blogapi.model.Category; +import com.sopromadze.blogapi.model.Post; +import com.sopromadze.blogapi.model.Tag; +import com.sopromadze.blogapi.model.user.User; +import com.sopromadze.blogapi.payload.ApiResponse; +import com.sopromadze.blogapi.payload.PagedResponse; +import com.sopromadze.blogapi.payload.PostRequest; +import com.sopromadze.blogapi.repository.CategoryRepository; +import com.sopromadze.blogapi.repository.PostRepository; +import com.sopromadze.blogapi.repository.TagRepository; +import com.sopromadze.blogapi.repository.UserRepository; +import com.sopromadze.blogapi.security.UserPrincipal; +import com.sopromadze.blogapi.utils.AppUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.*; + +@RunWith(SpringRunner.class) +public class PostServiceImplTests { + + @Mock + private AppUtils appUtils; + + @Mock + private PostRepository postRepository; + + @Mock + private UserRepository userRepository; + + @Mock + private CategoryRepository categoryRepository; + + @Mock + private TagRepository tagRepository; + + @InjectMocks + private PostServiceImpl postService; + + @Test + public void getAllPosts_whenNoPostsFound_thenReturnEmptyList() { + Mockito.when(postRepository.findAll(Mockito.any(Pageable.class))).thenReturn(Page.empty()); + + PagedResponse response = postService.getAllPosts(1, 2); + + Assert.assertEquals(0, response.getContent().size()); + Assert.assertEquals(Collections.emptyList(), response.getContent()); + } + + @Test + public void getAllPosts_whenPostsFound_thenReturnContent() { + Page page = Mockito.mock(Page.class); + + Mockito.when(page.getTotalPages()).thenReturn(1); + Mockito.when(page.getTotalElements()).thenReturn(1L); + Mockito.when(page.getNumber()).thenReturn(0); + Mockito.when(page.getSize()).thenReturn(1); + Mockito.when(page.getNumberOfElements()).thenReturn(1); + Mockito.when(page.getContent()).thenReturn(createPostList()); + + Mockito.when(postRepository.findAll(Mockito.any(Pageable.class))).thenReturn(page); + + PagedResponse response = postService.getAllPosts(1, 2); + + Assert.assertNotNull(response.getContent()); + Assert.assertEquals(1, response.getContent().size()); + } + + @Test + public void getPostsByCreatedBy_whenNoPostsFound_thenReturnEmptyList() { + User fakeUser = new User(); + fakeUser.setId(1L); + Mockito.when(userRepository.getUserByName(Mockito.anyString())).thenReturn(fakeUser); + Mockito.when(postRepository.findByCreatedBy(Mockito.anyLong(), Mockito.any(Pageable.class))).thenReturn(Page.empty()); + + PagedResponse response = postService.getPostsByCreatedBy("john.doe", 1, 2); + + Assert.assertEquals(0, response.getContent().size()); + Assert.assertEquals(Collections.emptyList(), response.getContent()); + } + + @Test + public void getPostsByCreatedBy_whenPostsFound_thenReturnContent() { + Page page = Mockito.mock(Page.class); + User fakeUser = new User(); + fakeUser.setId(1L); + + Mockito.when(page.getTotalPages()).thenReturn(1); + Mockito.when(page.getTotalElements()).thenReturn(1L); + Mockito.when(page.getNumber()).thenReturn(0); + Mockito.when(page.getSize()).thenReturn(1); + Mockito.when(page.getNumberOfElements()).thenReturn(1); + Mockito.when(page.getContent()).thenReturn(createPostList()); + + Mockito.when(userRepository.getUserByName(Mockito.anyString())).thenReturn(fakeUser); + Mockito.when(postRepository.findByCreatedBy(Mockito.anyLong(), Mockito.any(Pageable.class))).thenReturn(page); + + PagedResponse response = postService.getPostsByCreatedBy("john.doe", 1, 2); + + Assert.assertNotNull(response.getContent()); + Assert.assertEquals(1, response.getContent().size()); + } + + @Test(expected = ResourceNotFoundException.class) + public void getPostsByCategory_whenCategoryNotFound_thenThrowException() { + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + postService.getPostsByCategory(1L, 1, 2); + } + + @Test + public void getPostsByCategory_whenNoPostsFound_thenReturnEmptyList() { + Category category = new Category(); + category.setId(1L); + + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(category)); + Mockito.when(postRepository.findByCategory(Mockito.anyLong(), Mockito.any(Pageable.class))).thenReturn(Page.empty()); + + PagedResponse response = postService.getPostsByCategory(1L, 1, 2); + + Assert.assertEquals(0, response.getContent().size()); + Assert.assertEquals(Collections.emptyList(), response.getContent()); + } + + @Test + public void getPostsByCategory_whenPostsFound_thenReturnContent() { + Page page = Mockito.mock(Page.class); + Category category = new Category(); + category.setId(1L); + + Mockito.when(page.getTotalPages()).thenReturn(1); + Mockito.when(page.getTotalElements()).thenReturn(1L); + Mockito.when(page.getNumber()).thenReturn(0); + Mockito.when(page.getSize()).thenReturn(1); + Mockito.when(page.getNumberOfElements()).thenReturn(1); + Mockito.when(page.getContent()).thenReturn(createPostList()); + + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(category)); + Mockito.when(postRepository.findByCategory(Mockito.anyLong(), Mockito.any(Pageable.class))).thenReturn(page); + + PagedResponse response = postService.getPostsByCategory(1L, 1, 2); + + Assert.assertNotNull(response.getContent()); + Assert.assertEquals(1, response.getContent().size()); + } + + @Test(expected = ResourceNotFoundException.class) + public void getPostsByTag_whenTagNotFound_thenThrowException() { + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + postService.getPostsByTag(1L, 1, 2); + } + + @Test + public void getPostsByTag_whenNoPostsFound_thenReturnEmptyList() { + Tag tag = new Tag(); + + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(tag)); + Mockito.when(postRepository.findByTags(Mockito.any(), Mockito.any())).thenReturn(Page.empty()); + + PagedResponse response = postService.getPostsByTag(1L, 1, 2); + + Assert.assertEquals(0, response.getContent().size()); + Assert.assertEquals(Collections.emptyList(), response.getContent()); + } + + @Test + public void getPostsByTag_whenPostsFound_thenReturnContent() { + Page page = Mockito.mock(Page.class); + Tag tag = new Tag(); + + Mockito.when(page.getTotalPages()).thenReturn(1); + Mockito.when(page.getTotalElements()).thenReturn(1L); + Mockito.when(page.getNumber()).thenReturn(0); + Mockito.when(page.getSize()).thenReturn(1); + Mockito.when(page.getNumberOfElements()).thenReturn(1); + Mockito.when(page.getContent()).thenReturn(createPostList()); + + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(tag)); + Mockito.when(postRepository.findByTags(Mockito.any(), Mockito.any())).thenReturn(page); + + PagedResponse response = postService.getPostsByTag(1L, 1, 2); + + Assert.assertNotNull(response.getContent()); + Assert.assertEquals(1, response.getContent().size()); + } + + @Test(expected = ResourceNotFoundException.class) + public void updatePost_whenPostNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + postService.updatePost(1L, new PostRequest(), fakeUserPrincipal); + } + + @Test(expected = ResourceNotFoundException.class) + public void updatePost_whenCategoryNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + PostRequest postRequest = new PostRequest(); + postRequest.setCategoryId(1L); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new Post())); + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + postService.updatePost(1L, postRequest, fakeUserPrincipal); + } + + @Test + public void updatePost_whenUserAuthorized_thenSavePost() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + PostRequest postRequest = new PostRequest(); + postRequest.setCategoryId(1L); + User user = new User(); + user.setId(1L); + Post post = new Post(); + post.setUser(user); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(post)); + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new Category())); + + postService.updatePost(1L, postRequest, fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void updatePost_whenUserNotAuthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + PostRequest postRequest = new PostRequest(); + postRequest.setCategoryId(1L); + User user = new User(); + user.setId(2L); + Post post = new Post(); + post.setUser(user); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(post)); + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new Category())); + + postService.updatePost(1L, postRequest, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertEquals(false, e.getApiResponse().getSuccess()); + Assert.assertNotNull(e.getApiResponse().getMessage()); + throw e; + } + } + + @Test(expected = ResourceNotFoundException.class) + public void deletePost_whenPostNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + postService.deletePost(1L, fakeUserPrincipal); + } + + @Test + public void deletePost_whenUserAuthorized_thenDeleteAndReturnSuccessResponse() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User user = new User(); + user.setId(1L); + Post post = new Post(); + post.setUser(user); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(post)); + + ApiResponse response = postService.deletePost(1L, fakeUserPrincipal); + + Assert.assertNotNull(response.getMessage()); + Assert.assertEquals(true, response.getSuccess()); + } + + @Test(expected = UnauthorizedException.class) + public void deletePost_whenUserNotAuthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User user = new User(); + user.setId(2L); + Post post = new Post(); + post.setUser(user); + + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(post)); + + postService.deletePost(1L, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertEquals(false, e.getApiResponse().getSuccess()); + Assert.assertNotNull(e.getApiResponse().getMessage()); + throw e; + } + } + + @Test(expected = ResourceNotFoundException.class) + public void addPost_whenUserNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(userRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + postService.addPost(new PostRequest(), fakeUserPrincipal); + } + + @Test(expected = ResourceNotFoundException.class) + public void addPost_whenCategoryNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + PostRequest postRequest = new PostRequest(); + postRequest.setCategoryId(1L); + + Mockito.when(userRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new User())); + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + postService.addPost(postRequest, fakeUserPrincipal); + } + + @Test + public void addPost_whenAllFound_thenAddPost() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + PostRequest postRequest = new PostRequest(); + postRequest.setCategoryId(1L); + Category category = new Category(); + category.setName("Test"); + List tags = new ArrayList<>(); + Post post = new Post(); + post.setTitle("Test Post"); + post.setBody("This is a test."); + post.setCategory(category); + post.setTags(tags); + + Mockito.when(userRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new User())); + Mockito.when(categoryRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new Category())); + Mockito.when(postRepository.save(Mockito.any())).thenReturn(post); + + postService.addPost(postRequest, fakeUserPrincipal); + } + + @Test(expected = ResourceNotFoundException.class) + public void getPost_whenPostNotFound_thenThrowException() { + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + postService.getPost(1L); + } + + @Test + public void getPost_whenPostFound_thenReturnPost() { + Mockito.when(postRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new Post())); + + postService.getPost(1L); + } + + private List createPostList() { + List list = new ArrayList<>(); + Post post = new Post(); + list.add(post); + return list; + } +} diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/TagServiceImplTests.java b/src/test/java/com/sopromadze/blogapi/service/impl/TagServiceImplTests.java new file mode 100644 index 00000000..ddbf7c0a --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/service/impl/TagServiceImplTests.java @@ -0,0 +1,213 @@ +package com.sopromadze.blogapi.service.impl; + +import com.sopromadze.blogapi.exception.ResourceNotFoundException; +import com.sopromadze.blogapi.exception.UnauthorizedException; +import com.sopromadze.blogapi.model.Tag; +import com.sopromadze.blogapi.model.role.RoleName; +import com.sopromadze.blogapi.payload.ApiResponse; +import com.sopromadze.blogapi.payload.PagedResponse; +import com.sopromadze.blogapi.repository.TagRepository; +import com.sopromadze.blogapi.security.UserPrincipal; +import com.sopromadze.blogapi.utils.AppUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.*; + +@RunWith(SpringRunner.class) +public class TagServiceImplTests { + + @Mock + private AppUtils appUtils; + + @Mock + private TagRepository tagRepository; + + @InjectMocks + private TagServiceImpl tagService; + + @Test + public void getAllTags_whenNoTagsFound_thenReturnEmptyList() { + Mockito.when(tagRepository.findAll(Mockito.any(Pageable.class))).thenReturn(Page.empty()); + + PagedResponse response = tagService.getAllTags(1, 2); + + Assert.assertEquals(0, response.getContent().size()); + Assert.assertEquals(Collections.emptyList(), response.getContent()); + } + + @Test + public void getAllTags_whenTagsFound_thenReturnContent() { + Page page = Mockito.mock(Page.class); + + Mockito.when(page.getTotalPages()).thenReturn(1); + Mockito.when(page.getTotalElements()).thenReturn(1L); + Mockito.when(page.getNumber()).thenReturn(0); + Mockito.when(page.getSize()).thenReturn(1); + Mockito.when(page.getNumberOfElements()).thenReturn(1); + Mockito.when(page.getContent()).thenReturn(createTagList()); + + Mockito.when(tagRepository.findAll(Mockito.any(Pageable.class))).thenReturn(page); + + PagedResponse response = tagService.getAllTags(1, 2); + + Assert.assertNotNull(response.getContent()); + Assert.assertEquals(1, response.getContent().size()); + } + + @Test(expected = ResourceNotFoundException.class) + public void getTag_whenTagNotFound_thenThrowException() { + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + tagService.getTag(1L); + } + + @Test + public void getTag_whenTagFound_thenReturnTag() { + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(new Tag())); + + tagService.getTag(1L); + } + + @Test(expected = ResourceNotFoundException.class) + public void updateTag_whenTagNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + tagService.updateTag(1L, new Tag(), fakeUserPrincipal); + } + + @Test + public void updateTag_whenUserMatches_thenSaveTag() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Tag tag = new Tag(); + tag.setName("newName"); + tag.setCreatedBy(1L); + + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(tag)); + + tagService.updateTag(1L, tag, fakeUserPrincipal); + } + + @Test + public void updateTag_whenUserAdmin_thenSaveTag() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Tag tag = new Tag(); + tag.setName("newName"); + tag.setCreatedBy(2L); + + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(tag)); + + tagService.updateTag(1L, tag, fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void updateTag_whenUserNotAuthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Tag tag = new Tag(); + tag.setName("newName"); + tag.setCreatedBy(2L); + + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(tag)); + + tagService.updateTag(1L, tag, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertNotNull(e.getApiResponse().getMessage()); + Assert.assertFalse(e.getApiResponse().getSuccess()); + throw e; + } + } + + @Test(expected = ResourceNotFoundException.class) + public void deleteTag_whenTagNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + tagService.deleteTag(1L, fakeUserPrincipal); + } + + @Test + public void deleteTag_whenUserAuthorized_thenDeleteTag() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Tag tag = new Tag(); + tag.setName("newName"); + tag.setCreatedBy(1L); + + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(tag)); + + ApiResponse response = tagService.deleteTag(1L, fakeUserPrincipal); + + Assert.assertNotNull(response.getMessage()); + Assert.assertTrue(response.getSuccess()); + } + + @Test + public void deleteTag_whenUserAdmin_thenDeleteTag() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Tag tag = new Tag(); + tag.setName("newName"); + tag.setCreatedBy(2L); + + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(tag)); + + ApiResponse response = tagService.deleteTag(1L, fakeUserPrincipal); + + Assert.assertNotNull(response.getMessage()); + Assert.assertTrue(response.getSuccess()); + } + + @Test(expected = UnauthorizedException.class) + public void deleteTag_whenUserNotAuthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + Tag tag = new Tag(); + tag.setName("newName"); + tag.setCreatedBy(2L); + + Mockito.when(tagRepository.findById(Mockito.anyLong())).thenReturn(Optional.of(tag)); + + tagService.deleteTag(1L, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertNotNull(e.getApiResponse().getMessage()); + Assert.assertFalse(e.getApiResponse().getSuccess()); + throw e; + } + } + + private List createTagList() { + List list = new ArrayList<>(); + Tag tag = new Tag(); + list.add(tag); + return list; + } +} diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/TodoServiceImplTests.java b/src/test/java/com/sopromadze/blogapi/service/impl/TodoServiceImplTests.java new file mode 100644 index 00000000..ded710f1 --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/service/impl/TodoServiceImplTests.java @@ -0,0 +1,249 @@ +package com.sopromadze.blogapi.service.impl; + +import com.sopromadze.blogapi.exception.ResourceNotFoundException; +import com.sopromadze.blogapi.exception.UnauthorizedException; +import com.sopromadze.blogapi.model.Todo; +import com.sopromadze.blogapi.model.user.User; +import com.sopromadze.blogapi.payload.PagedResponse; +import com.sopromadze.blogapi.repository.TodoRepository; +import com.sopromadze.blogapi.repository.UserRepository; +import com.sopromadze.blogapi.security.UserPrincipal; +import com.sopromadze.blogapi.utils.AppUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.*; + +@RunWith(SpringRunner.class) +public class TodoServiceImplTests { + + @Mock + private AppUtils appUtils; + + @Mock + private TodoRepository todoRepository; + + @Mock + private UserRepository userRepository; + + @InjectMocks + private TodoServiceImpl todoService; + + private UserPrincipal fakeUserPrincipal; + + @Before + public void setup() { + Collection authorities = new ArrayList<>(); + fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + } + + @Test(expected = ResourceNotFoundException.class) + public void completeTodo_whenTodoNotFound_thenThrowException() { + Mockito.when(todoRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + todoService.completeTodo(1L, fakeUserPrincipal); + } + + @Test + public void completeTodo_whenUserMatches_thenSaveTodo() { + User testUser = new User(); + testUser.setId(1L); + Todo todo = new Todo(); + todo.setUser(testUser); + + Mockito.when(todoRepository.findById(Mockito.any())).thenReturn(Optional.of(todo)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(testUser); + + todoService.completeTodo(1L, fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void completeTodo_whenUserNotAuthorized_thenThrowException() { + try { + User testUser = new User(); + testUser.setId(1L); + User todoUser = new User(); + todoUser.setId(2L); + Todo todo = new Todo(); + todo.setUser(todoUser); + + Mockito.when(todoRepository.findById(Mockito.any())).thenReturn(Optional.of(todo)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(testUser); + + todoService.completeTodo(1L, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertNotNull(e.getApiResponse().getMessage()); + Assert.assertFalse(e.getApiResponse().getSuccess()); + throw e; + } + } + + @Test(expected = ResourceNotFoundException.class) + public void unCompleteTodo_whenTodoNotFound_thenThrowException() { + Mockito.when(todoRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + todoService.unCompleteTodo(1L, fakeUserPrincipal); + } + + @Test + public void unCompleteTodo_whenUserMatches_thenSaveTodo() { + User testUser = new User(); + testUser.setId(1L); + Todo todo = new Todo(); + todo.setUser(testUser); + + Mockito.when(todoRepository.findById(Mockito.any())).thenReturn(Optional.of(todo)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(testUser); + + todoService.unCompleteTodo(1L, fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void unCompleteTodo_whenUserNotAuthorized_thenThrowException() { + try { + User testUser = new User(); + testUser.setId(1L); + User todoUser = new User(); + todoUser.setId(2L); + Todo todo = new Todo(); + todo.setUser(todoUser); + + Mockito.when(todoRepository.findById(Mockito.any())).thenReturn(Optional.of(todo)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(testUser); + + todoService.unCompleteTodo(1L, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertNotNull(e.getApiResponse().getMessage()); + Assert.assertFalse(e.getApiResponse().getSuccess()); + throw e; + } + } + + @Test + public void getAllTodos_whenNoTodoFound_thenReturnEmptyList() { + Mockito.when(todoRepository.findByCreatedBy(Mockito.anyLong(), Mockito.any(Pageable.class))).thenReturn(Page.empty()); + + PagedResponse response = todoService.getAllTodos(fakeUserPrincipal, 1, 2); + + Assert.assertEquals(0, response.getContent().size()); + Assert.assertEquals(Collections.emptyList(), response.getContent()); + } + + @Test + public void getAllTodos_whenTodoFound_thenReturnContent() { + Page page = Mockito.mock(Page.class); + + Mockito.when(page.getTotalPages()).thenReturn(1); + Mockito.when(page.getTotalElements()).thenReturn(1L); + Mockito.when(page.getNumber()).thenReturn(0); + Mockito.when(page.getSize()).thenReturn(1); + Mockito.when(page.getNumberOfElements()).thenReturn(1); + Mockito.when(page.getContent()).thenReturn(createTodoList()); + + Mockito.when(todoRepository.findByCreatedBy(Mockito.anyLong(), Mockito.any(Pageable.class))).thenReturn(page); + + PagedResponse response = todoService.getAllTodos(fakeUserPrincipal, 1, 2); + + Assert.assertNotNull(response.getContent()); + Assert.assertEquals(1, response.getContent().size()); + } + + @Test(expected = ResourceNotFoundException.class) + public void getTodo_whenTodoNotFound_thenThrowException() { + Mockito.when(todoRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + todoService.getTodo(1L, fakeUserPrincipal); + } + + @Test + public void getTodo_whenUserMatches_thenReturnTodo() { + User testUser = new User(); + testUser.setId(1L); + Todo todo = new Todo(); + todo.setUser(testUser); + + Mockito.when(todoRepository.findById(Mockito.any())).thenReturn(Optional.of(todo)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(testUser); + + todoService.getTodo(1L, fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void getTodo_whenUserNotAuthorized_thenThrowException() { + try { + User testUser = new User(); + testUser.setId(1L); + User todoUser = new User(); + todoUser.setId(2L); + Todo todo = new Todo(); + todo.setUser(todoUser); + + Mockito.when(todoRepository.findById(Mockito.any())).thenReturn(Optional.of(todo)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(testUser); + + todoService.getTodo(1L, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertNotNull(e.getApiResponse().getMessage()); + Assert.assertFalse(e.getApiResponse().getSuccess()); + throw e; + } + } + + @Test(expected = ResourceNotFoundException.class) + public void updateTodo_whenTodoNotFound_thenThrowException() { + Mockito.when(todoRepository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); + + todoService.updateTodo(1L, new Todo(), fakeUserPrincipal); + } + + @Test + public void updateTodo_whenUserMatches_thenSaveTodo() { + User testUser = new User(); + testUser.setId(1L); + Todo todo = new Todo(); + todo.setUser(testUser); + + Mockito.when(todoRepository.findById(Mockito.any())).thenReturn(Optional.of(todo)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(testUser); + + todoService.updateTodo(1L, todo, fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void updateTodo_whenUserNotAuthorized_thenThrowException() { + try { + User testUser = new User(); + testUser.setId(1L); + User todoUser = new User(); + todoUser.setId(2L); + Todo todo = new Todo(); + todo.setUser(todoUser); + + Mockito.when(todoRepository.findById(Mockito.any())).thenReturn(Optional.of(todo)); + Mockito.when(userRepository.getUser(Mockito.any())).thenReturn(testUser); + + todoService.updateTodo(1L, todo, fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertNotNull(e.getApiResponse().getMessage()); + Assert.assertFalse(e.getApiResponse().getSuccess()); + throw e; + } + } + + private List createTodoList() { + List list = new ArrayList<>(); + Todo todo = new Todo(); + list.add(todo); + return list; + } +} diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/UserServiceImplTests.java b/src/test/java/com/sopromadze/blogapi/service/impl/UserServiceImplTests.java new file mode 100644 index 00000000..38e67dee --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/service/impl/UserServiceImplTests.java @@ -0,0 +1,361 @@ +package com.sopromadze.blogapi.service.impl; + +import com.sopromadze.blogapi.exception.*; +import com.sopromadze.blogapi.model.role.Role; +import com.sopromadze.blogapi.model.role.RoleName; +import com.sopromadze.blogapi.model.user.User; +import com.sopromadze.blogapi.payload.ApiResponse; +import com.sopromadze.blogapi.payload.InfoRequest; +import com.sopromadze.blogapi.repository.PostRepository; +import com.sopromadze.blogapi.repository.RoleRepository; +import com.sopromadze.blogapi.repository.UserRepository; +import com.sopromadze.blogapi.security.UserPrincipal; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Optional; + +@RunWith(SpringRunner.class) +public class UserServiceImplTests { + + @Mock + private UserRepository userRepository; + + @Mock + private PostRepository postRepository; + + @Mock + private RoleRepository roleRepository; + + @Mock + private PasswordEncoder passwordEncoder; + + @InjectMocks + private UserServiceImpl userService; + + @Test(expected = BadRequestException.class) + public void addUser_whenUsernameAlreadyTaken_thenThrowException() { + try { + User user = new User(); + user.setUsername("john.doe"); + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(true); + + userService.addUser(user); + } catch (BadRequestException e) { + Assert.assertFalse(e.getApiResponse().getSuccess()); + Assert.assertNotNull(e.getApiResponse().getMessage()); + throw e; + } + } + + @Test(expected = BadRequestException.class) + public void addUser_whenEmailAlreadyTaken_thenThrowException() { + try { + User user = new User(); + user.setUsername("john.doe"); + user.setEmail("john.doe@example.com"); + + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(false); + Mockito.when(userRepository.existsByEmail(Mockito.anyString())).thenReturn(true); + + userService.addUser(user); + } catch (BadRequestException e) { + Assert.assertFalse(e.getApiResponse().getSuccess()); + Assert.assertNotNull(e.getApiResponse().getMessage()); + throw e; + } + } + + @Test(expected = AppException.class) + public void addUser_whenUserRoleNotSet_thenThrowException() { + User user = new User(); + user.setUsername("john.doe"); + user.setEmail("john.doe@example.com"); + + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(false); + Mockito.when(userRepository.existsByEmail(Mockito.anyString())).thenReturn(false); + + userService.addUser(user); + } + + @Test + public void addUser_whenUserAvailable_thenSaveUser() { + User user = new User(); + user.setUsername("john.doe"); + user.setEmail("john.doe@example.com"); + + Mockito.when(userRepository.existsByUsername(Mockito.anyString())).thenReturn(false); + Mockito.when(userRepository.existsByEmail(Mockito.anyString())).thenReturn(false); + Mockito.when(roleRepository.findByName(Mockito.any())).thenReturn(Optional.of(new Role())); + + userService.addUser(user); + } + + @Test + public void updateUser_whenUserAuthorized_thenSaveUser() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User user = new User(); + user.setUsername("john.doe"); + user.setEmail("john.doe@example.com"); + user.setId(1L); + + Mockito.when(userRepository.getUserByName(Mockito.anyString())).thenReturn(user); + + userService.updateUser(user, "john.doe", fakeUserPrincipal); + } + + @Test + public void updateUser_whenUserAdmin_thenSaveUser() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User user = new User(); + user.setUsername("john.doe"); + user.setEmail("john.doe@example.com"); + user.setId(2L); + + Mockito.when(userRepository.getUserByName(Mockito.anyString())).thenReturn(user); + + userService.updateUser(user, "john.doe", fakeUserPrincipal); + } + + @Test(expected = UnauthorizedException.class) + public void updateUser_whenUserNotAuthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User user = new User(); + user.setUsername("john.doe"); + user.setEmail("john.doe@example.com"); + user.setId(2L); + + Mockito.when(userRepository.getUserByName(Mockito.anyString())).thenReturn(user); + + userService.updateUser(user, "john.doe", fakeUserPrincipal); + } catch (UnauthorizedException e) { + Assert.assertFalse(e.getApiResponse().getSuccess()); + Assert.assertNotNull(e.getApiResponse().getMessage()); + throw e; + } + } + + @Test(expected = ResourceNotFoundException.class) + public void deleteUser_whenUserNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + + Mockito.when(userRepository.findByUsername(Mockito.anyString())).thenReturn(Optional.empty()); + + userService.deleteUser("john.doe", fakeUserPrincipal); + } + + @Test(expected = AccessDeniedException.class) + public void deleteUser_whenNotCurrentUserOrAdmin_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User user = new User(); + user.setId(2L); + + Mockito.when(userRepository.findByUsername(Mockito.anyString())).thenReturn(Optional.of(user)); + + userService.deleteUser("john.doe", fakeUserPrincipal); + } catch (AccessDeniedException e) { + Assert.assertFalse(e.getApiResponse().getSuccess()); + Assert.assertNotNull(e.getApiResponse().getMessage()); + throw e; + } + } + + @Test + public void deleteUser_whenUserMatches_thenDeleteUser() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User user = new User(); + user.setId(1L); + + Mockito.when(userRepository.findByUsername(Mockito.anyString())).thenReturn(Optional.of(user)); + + ApiResponse response = userService.deleteUser("john.doe", fakeUserPrincipal); + Assert.assertTrue(response.getSuccess()); + Assert.assertNotNull(response.getMessage()); + } + + @Test + public void deleteUser_whenUserAdmin_thenDeleteUser() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + User user = new User(); + user.setId(2L); + + Mockito.when(userRepository.findByUsername(Mockito.anyString())).thenReturn(Optional.of(user)); + + ApiResponse response = userService.deleteUser("john.doe", fakeUserPrincipal); + Assert.assertTrue(response.getSuccess()); + Assert.assertNotNull(response.getMessage()); + } + + @Test(expected = AppException.class) + public void giveAdmin_whenAdminRoleNotFound_thenThrowException() { + Mockito.when(userRepository.getUserByName(Mockito.anyString())).thenReturn(new User()); + Mockito.when(roleRepository.findByName(Mockito.any())).thenReturn(Optional.empty()); + + userService.giveAdmin("john.doe"); + } + + @Test(expected = AppException.class) + public void giveAdmin_whenUserRoleNotFound_thenThrowException() { + Mockito.when(userRepository.getUserByName(Mockito.anyString())).thenReturn(new User()); + Mockito.when(roleRepository.findByName(RoleName.ROLE_ADMIN)).thenReturn(Optional.of(new Role())); + Mockito.when(roleRepository.findByName(RoleName.ROLE_USER)).thenReturn(Optional.empty()); + + userService.giveAdmin("john.doe"); + } + + @Test + public void giveAdmin_whenUserUpdated_thenReturnSuccessResponse() { + Mockito.when(userRepository.getUserByName(Mockito.anyString())).thenReturn(new User()); + Mockito.when(roleRepository.findByName(Mockito.any())).thenReturn(Optional.of(new Role())); + + ApiResponse response = userService.giveAdmin("john.doe"); + Assert.assertTrue(response.getSuccess()); + Assert.assertNotNull(response.getMessage()); + } + + @Test(expected = AppException.class) + public void removeAdmin_whenUserRoleNotFound_thenThrowException() { + Mockito.when(userRepository.getUserByName(Mockito.anyString())).thenReturn(new User()); + Mockito.when(roleRepository.findByName(Mockito.any())).thenReturn(Optional.empty()); + + userService.removeAdmin("john.doe"); + } + + @Test + public void removeAdmin_whenUserUpdated_thenReturnSuccessResponse() { + Mockito.when(userRepository.getUserByName(Mockito.anyString())).thenReturn(new User()); + Mockito.when(roleRepository.findByName(Mockito.any())).thenReturn(Optional.of(new Role())); + + ApiResponse response = userService.removeAdmin("john.doe"); + Assert.assertTrue(response.getSuccess()); + Assert.assertNotNull(response.getMessage()); + } + + @Test(expected = ResourceNotFoundException.class) + public void setOrUpdateInfo_whenUserNotFound_thenThrowException() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + InfoRequest infoRequest = new InfoRequest(); + + Mockito.when(userRepository.findByUsername(Mockito.anyString())).thenReturn(Optional.empty()); + + userService.setOrUpdateInfo(fakeUserPrincipal, infoRequest); + } + + @Test + public void setOrUpdateInfo_whenUserAuthorized_thenReturnUserProfile() { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + InfoRequest infoRequest = new InfoRequest(); + infoRequest.setLng("-104.990250"); + infoRequest.setLat("39.739235"); + infoRequest.setStreet("1234 W Park Ln"); + infoRequest.setSuite("12345"); + infoRequest.setCity("New York"); + infoRequest.setZipcode("00000"); + infoRequest.setCompanyName("The Company Inc."); + infoRequest.setCatchPhrase("We Are A Company"); + infoRequest.setBs("Test"); + infoRequest.setPhone("555-555-5555"); + infoRequest.setWebsite("https://example.com"); + User user = new User(); + user.setId(1L); + + Mockito.when(userRepository.findByUsername(Mockito.anyString())).thenReturn(Optional.of(user)); + Mockito.when(userRepository.save(Mockito.any())).thenReturn(user); + Mockito.when(postRepository.countByCreatedBy(Mockito.anyLong())).thenReturn(3L); + + userService.setOrUpdateInfo(fakeUserPrincipal, infoRequest); + } + + @Test + public void setOrUpdateInfo_whenUserAdmin_thenReturnUserProfile() { + Collection authorities = new ArrayList<>(); + authorities.add(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + InfoRequest infoRequest = new InfoRequest(); + infoRequest.setLng("-104.990250"); + infoRequest.setLat("39.739235"); + infoRequest.setStreet("1234 W Park Ln"); + infoRequest.setSuite("12345"); + infoRequest.setCity("New York"); + infoRequest.setZipcode("00000"); + infoRequest.setCompanyName("The Company Inc."); + infoRequest.setCatchPhrase("We Are A Company"); + infoRequest.setBs("Test"); + infoRequest.setPhone("555-555-5555"); + infoRequest.setWebsite("https://example.com"); + User user = new User(); + user.setId(2L); + + Mockito.when(userRepository.findByUsername(Mockito.anyString())).thenReturn(Optional.of(user)); + Mockito.when(userRepository.save(Mockito.any())).thenReturn(user); + Mockito.when(postRepository.countByCreatedBy(Mockito.anyLong())).thenReturn(3L); + + userService.setOrUpdateInfo(fakeUserPrincipal, infoRequest); + } + + @Test(expected = AccessDeniedException.class) + public void setOrUpdateInfo_whenUserNotAuthorized_thenThrowException() { + try { + Collection authorities = new ArrayList<>(); + UserPrincipal fakeUserPrincipal = new UserPrincipal(1L, "John", "Doe", "john.doe", + "john.doe@example.com", "password123", authorities); + InfoRequest infoRequest = new InfoRequest(); + infoRequest.setLng("-104.990250"); + infoRequest.setLat("39.739235"); + infoRequest.setStreet("1234 W Park Ln"); + infoRequest.setSuite("12345"); + infoRequest.setCity("New York"); + infoRequest.setZipcode("00000"); + infoRequest.setCompanyName("The Company Inc."); + infoRequest.setCatchPhrase("We Are A Company"); + infoRequest.setBs("Test"); + infoRequest.setPhone("555-555-5555"); + infoRequest.setWebsite("https://example.com"); + User user = new User(); + user.setId(2L); + + Mockito.when(userRepository.findByUsername(Mockito.anyString())).thenReturn(Optional.of(user)); + Mockito.when(userRepository.save(Mockito.any())).thenReturn(user); + Mockito.when(postRepository.countByCreatedBy(Mockito.anyLong())).thenReturn(3L); + + userService.setOrUpdateInfo(fakeUserPrincipal, infoRequest); + } catch (AccessDeniedException e) { + Assert.assertFalse(e.getApiResponse().getSuccess()); + Assert.assertNotNull(e.getApiResponse().getMessage()); + Assert.assertEquals(403, e.getApiResponse().getStatus().value()); + throw e; + } + } +} diff --git a/src/test/java/com/sopromadze/blogapi/utils/AppUtilsTests.java b/src/test/java/com/sopromadze/blogapi/utils/AppUtilsTests.java new file mode 100644 index 00000000..5ce1fe4d --- /dev/null +++ b/src/test/java/com/sopromadze/blogapi/utils/AppUtilsTests.java @@ -0,0 +1,49 @@ +package com.sopromadze.blogapi.utils; + +import com.sopromadze.blogapi.exception.BlogapiException; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +public class AppUtilsTests { + + @Test(expected = BlogapiException.class) + public void validatePageNumberAndSize_whenPageIsLessThanZero_thenThrowException() { + try { + AppUtils.validatePageNumberAndSize(-1, 2); + } catch (BlogapiException e) { + Assert.assertEquals(400, e.getStatus().value()); + Assert.assertNotNull(e.getMessage()); + throw e; + } + } + + @Test(expected = BlogapiException.class) + public void validatePageNumberAndSize_whenSizeIsLessThanZero_thenThrowException() { + try { + AppUtils.validatePageNumberAndSize(1, -2); + } catch (BlogapiException e) { + Assert.assertEquals(400, e.getStatus().value()); + Assert.assertNotNull(e.getMessage()); + throw e; + } + } + + @Test(expected = BlogapiException.class) + public void validatePageNumberAndSize_whenSizeIsGreaterThanMaxSize_thenThrowException() { + try { + AppUtils.validatePageNumberAndSize(1, AppConstants.MAX_PAGE_SIZE + 1); + } catch (BlogapiException e) { + Assert.assertEquals(400, e.getStatus().value()); + Assert.assertNotNull(e.getMessage()); + throw e; + } + } + + @Test + public void validatePageNumberAndSize_whenPageAndSizeValid_thenDoNothing() { + AppUtils.validatePageNumberAndSize(1, 2); + } +}