diff --git a/pom.xml b/pom.xml
index 2e16331f..42f4e000 100644
--- a/pom.xml
+++ b/pom.xml
@@ -160,11 +160,36 @@
h2
runtime
+
+ org.jacoco
+ jacoco-maven-plugin
+ 0.8.7
+
+
+
+ org.jacoco
+ jacoco-maven-plugin
+ 0.8.7
+
+
+
+ prepare-agent
+
+
+
+ report
+ prepare-package
+
+ report
+
+
+
+
org.springframework.boot
spring-boot-maven-plugin
@@ -179,6 +204,14 @@
-
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 9
+ 9
+
+
+
diff --git a/src/main/java/com/sopromadze/blogapi/controller/AlbumController.java b/src/main/java/com/sopromadze/blogapi/controller/AlbumController.java
index 20d29835..ea7dced6 100644
--- a/src/main/java/com/sopromadze/blogapi/controller/AlbumController.java
+++ b/src/main/java/com/sopromadze/blogapi/controller/AlbumController.java
@@ -14,7 +14,6 @@
import com.sopromadze.blogapi.utils.AppConstants;
import com.sopromadze.blogapi.utils.AppUtils;
import lombok.RequiredArgsConstructor;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -46,36 +45,36 @@ public ResponseEntity handleExceptions(ResponseEntityErrorException
}
@GetMapping
- public PagedResponse getAllAlbums(
+ public ResponseEntity> getAllAlbums(
@RequestParam(name = "page", required = false, defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) Integer page,
@RequestParam(name = "size", required = false, defaultValue = AppConstants.DEFAULT_PAGE_SIZE) Integer size) {
AppUtils.validatePageNumberAndSize(page, size);
- return albumService.getAllAlbums(page, size);
+ return ResponseEntity.status(HttpStatus.OK).body(albumService.getAllAlbums(page, size));
}
@PostMapping
@PreAuthorize("hasRole('USER')")
public ResponseEntity addAlbum(@Valid @RequestBody AlbumRequest albumRequest, @CurrentUser UserPrincipal currentUser) {
- return albumService.addAlbum(albumRequest, currentUser);
+ return ResponseEntity.status(HttpStatus.CREATED).body(albumService.addAlbum(albumRequest, currentUser));
}
@GetMapping("/{id}")
public ResponseEntity getAlbum(@PathVariable(name = "id") Long id) {
- return albumService.getAlbum(id);
+ return ResponseEntity.status(HttpStatus.OK).body(albumService.getAlbum(id));
}
@PutMapping("/{id}")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity updateAlbum(@PathVariable(name = "id") Long id, @Valid @RequestBody AlbumRequest newAlbum,
@CurrentUser UserPrincipal currentUser) {
- return albumService.updateAlbum(id, newAlbum, currentUser);
+ return ResponseEntity.status(HttpStatus.CREATED).body(albumService.updateAlbum(id, newAlbum, currentUser));
}
@DeleteMapping("/{id}")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity deleteAlbum(@PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser) {
- return albumService.deleteAlbum(id, currentUser);
+ return ResponseEntity.status(HttpStatus.OK).body(albumService.deleteAlbum(id, currentUser));
}
@GetMapping("/{id}/photos")
diff --git a/src/main/java/com/sopromadze/blogapi/controller/CategoryController.java b/src/main/java/com/sopromadze/blogapi/controller/CategoryController.java
index ff843a68..a926b655 100644
--- a/src/main/java/com/sopromadze/blogapi/controller/CategoryController.java
+++ b/src/main/java/com/sopromadze/blogapi/controller/CategoryController.java
@@ -10,6 +10,7 @@
import com.sopromadze.blogapi.utils.AppConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
@@ -42,20 +43,19 @@ public PagedResponse getAllCategories(
@PreAuthorize("hasRole('USER')")
public ResponseEntity addCategory(@Valid @RequestBody Category category,
@CurrentUser UserPrincipal currentUser) {
-
- return categoryService.addCategory(category, currentUser);
+ return ResponseEntity.status(HttpStatus.CREATED).body(categoryService.addCategory(category, currentUser));
}
@GetMapping("/{id}")
public ResponseEntity getCategory(@PathVariable(name = "id") Long id) {
- return categoryService.getCategory(id);
+ return ResponseEntity.status(HttpStatus.OK).body(categoryService.getCategory(id));
}
@PutMapping("/{id}")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity updateCategory(@PathVariable(name = "id") Long id,
@Valid @RequestBody Category category, @CurrentUser UserPrincipal currentUser) throws UnauthorizedException {
- return categoryService.updateCategory(id, category, currentUser);
+ return ResponseEntity.status(HttpStatus.OK).body(categoryService.updateCategory(id, category, currentUser));
}
@DeleteMapping("/{id}")
diff --git a/src/main/java/com/sopromadze/blogapi/controller/CommentController.java b/src/main/java/com/sopromadze/blogapi/controller/CommentController.java
index f23a31ef..1f1ad65d 100644
--- a/src/main/java/com/sopromadze/blogapi/controller/CommentController.java
+++ b/src/main/java/com/sopromadze/blogapi/controller/CommentController.java
@@ -34,13 +34,13 @@ public class CommentController {
private final CommentService commentService;
@GetMapping
- public ResponseEntity> getAllComments(@PathVariable(name = "postId") Long postId,
+ public PagedResponse getAllComments(@PathVariable(name = "postId") Long postId,
@RequestParam(name = "page", required = false, defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) Integer page,
@RequestParam(name = "size", required = false, defaultValue = AppConstants.DEFAULT_PAGE_SIZE) Integer size) {
PagedResponse allComments = commentService.getAllComments(postId, page, size);
- return new ResponseEntity< >(allComments, HttpStatus.OK);
+ return allComments;
}
@PostMapping
@@ -49,15 +49,15 @@ public ResponseEntity addComment(@Valid @RequestBody CommentRequest com
@PathVariable(name = "postId") Long postId, @CurrentUser UserPrincipal currentUser) {
Comment newComment = commentService.addComment(commentRequest, postId, currentUser);
- return new ResponseEntity<>(newComment, HttpStatus.CREATED);
+ return ResponseEntity.status(HttpStatus.CREATED).body(newComment);
}
@GetMapping("/{id}")
- public ResponseEntity getComment(@PathVariable(name = "postId") Long postId,
+ public Comment getComment(@PathVariable(name = "postId") Long postId,
@PathVariable(name = "id") Long id) {
Comment comment = commentService.getComment(postId, id);
- return new ResponseEntity<>(comment, HttpStatus.OK);
+ return comment;
}
@PutMapping("/{id}")
@@ -74,7 +74,7 @@ public ResponseEntity updateComment(@PathVariable(name = "postId") Long
@DeleteMapping("/{id}")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity deleteComment(@PathVariable(name = "postId") Long postId,
- @PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser) {
+ @PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser) {
ApiResponse response = commentService.deleteComment(postId, id, currentUser);
diff --git a/src/main/java/com/sopromadze/blogapi/controller/PhotoController.java b/src/main/java/com/sopromadze/blogapi/controller/PhotoController.java
index c75f6b56..e8cd8c3d 100644
--- a/src/main/java/com/sopromadze/blogapi/controller/PhotoController.java
+++ b/src/main/java/com/sopromadze/blogapi/controller/PhotoController.java
@@ -1,5 +1,6 @@
package com.sopromadze.blogapi.controller;
+import com.sopromadze.blogapi.model.Photo;
import com.sopromadze.blogapi.payload.ApiResponse;
import com.sopromadze.blogapi.payload.PagedResponse;
import com.sopromadze.blogapi.payload.PhotoRequest;
@@ -9,7 +10,6 @@
import com.sopromadze.blogapi.service.PhotoService;
import com.sopromadze.blogapi.utils.AppConstants;
import lombok.RequiredArgsConstructor;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -24,6 +24,7 @@
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
+import java.util.List;
@RestController
@RequestMapping("/api/photos")
@@ -42,35 +43,35 @@ public PagedResponse getAllPhotos(
@PostMapping
@PreAuthorize("hasRole('USER')")
- public ResponseEntity addPhoto(@Valid @RequestBody PhotoRequest photoRequest,
+ public Photo addPhoto(@Valid @RequestBody PhotoRequest photoRequest,
@CurrentUser UserPrincipal currentUser) {
- PhotoResponse photoResponse = photoService.addPhoto(photoRequest, currentUser);
+ Photo photo = photoService.addPhoto(photoRequest, currentUser);
- return new ResponseEntity< >(photoResponse, HttpStatus.OK);
+ return photo;
}
@GetMapping("/{id}")
- public ResponseEntity getPhoto(@PathVariable(name = "id") Long id) {
- PhotoResponse photoResponse = photoService.getPhoto(id);
+ public Photo getPhoto(@PathVariable(name = "id") Long id) {
+ Photo photo = photoService.getPhoto(id);
- return new ResponseEntity< >(photoResponse, HttpStatus.OK);
+ return photo;
}
@PutMapping("/{id}")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
- public ResponseEntity updatePhoto(@PathVariable(name = "id") Long id,
- @Valid @RequestBody PhotoRequest photoRequest, @CurrentUser UserPrincipal currentUser) {
+ public Photo updatePhoto(@PathVariable(name = "id") Long id,
+ @Valid @RequestBody PhotoRequest photoRequest, @CurrentUser UserPrincipal currentUser) {
- PhotoResponse photoResponse = photoService.updatePhoto(id, photoRequest, currentUser);
+ Photo photo = photoService.updatePhoto(id, photoRequest, currentUser);
- return new ResponseEntity< >(photoResponse, HttpStatus.OK);
+ return photo;
}
@DeleteMapping("/{id}")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
- public ResponseEntity deletePhoto(@PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser) {
+ public ApiResponse deletePhoto(@PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser) {
ApiResponse apiResponse = photoService.deletePhoto(id, currentUser);
- return new ResponseEntity< >(apiResponse, HttpStatus.OK);
+ return apiResponse;
}
}
diff --git a/src/main/java/com/sopromadze/blogapi/controller/TagController.java b/src/main/java/com/sopromadze/blogapi/controller/TagController.java
index 455155a4..0e06c824 100644
--- a/src/main/java/com/sopromadze/blogapi/controller/TagController.java
+++ b/src/main/java/com/sopromadze/blogapi/controller/TagController.java
@@ -39,7 +39,7 @@ public ResponseEntity> getAllTags(
PagedResponse response = tagService.getAllTags(page, size);
- return new ResponseEntity< >(response, HttpStatus.OK);
+ return ResponseEntity.status(HttpStatus.OK).body(response);
}
@PostMapping
@@ -47,14 +47,14 @@ public ResponseEntity> getAllTags(
public ResponseEntity addTag(@Valid @RequestBody Tag tag, @CurrentUser UserPrincipal currentUser) {
Tag newTag = tagService.addTag(tag, currentUser);
- return new ResponseEntity< >(newTag, HttpStatus.CREATED);
+ return ResponseEntity.status(HttpStatus.CREATED).body(newTag);
}
@GetMapping("/{id}")
public ResponseEntity getTag(@PathVariable(name = "id") Long id) {
Tag tag = tagService.getTag(id);
- return new ResponseEntity< >(tag, HttpStatus.OK);
+ return ResponseEntity.status(HttpStatus.OK).body(tag);
}
@PutMapping("/{id}")
@@ -63,7 +63,7 @@ public ResponseEntity updateTag(@PathVariable(name = "id") Long id, @Valid
Tag updatedTag = tagService.updateTag(id, tag, currentUser);
- return new ResponseEntity< >(updatedTag, HttpStatus.OK);
+ return ResponseEntity.status(HttpStatus.OK).body(updatedTag);
}
@DeleteMapping("/{id}")
@@ -71,7 +71,7 @@ public ResponseEntity updateTag(@PathVariable(name = "id") Long id, @Valid
public ResponseEntity deleteTag(@PathVariable(name = "id") Long id, @CurrentUser UserPrincipal currentUser) {
ApiResponse apiResponse = tagService.deleteTag(id, currentUser);
- return new ResponseEntity< >(apiResponse, HttpStatus.OK);
+ return ResponseEntity.status(HttpStatus.OK).body(apiResponse);
}
}
diff --git a/src/main/java/com/sopromadze/blogapi/model/Tag.java b/src/main/java/com/sopromadze/blogapi/model/Tag.java
index a3cbd193..65a53d95 100644
--- a/src/main/java/com/sopromadze/blogapi/model/Tag.java
+++ b/src/main/java/com/sopromadze/blogapi/model/Tag.java
@@ -3,6 +3,7 @@
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sopromadze.blogapi.model.audit.UserDateAudit;
import com.sopromadze.blogapi.model.Post;
+import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
diff --git a/src/main/java/com/sopromadze/blogapi/repository/PostRepository.java b/src/main/java/com/sopromadze/blogapi/repository/PostRepository.java
index 5317ca9c..39edcac9 100644
--- a/src/main/java/com/sopromadze/blogapi/repository/PostRepository.java
+++ b/src/main/java/com/sopromadze/blogapi/repository/PostRepository.java
@@ -13,7 +13,7 @@
public interface PostRepository extends JpaRepository {
Page findByCreatedBy(Long userId, Pageable pageable);
- Page findByCategory(Long categoryId, Pageable pageable);
+ Page findByCategoryId(Long categoryId, Pageable pageable);
Page findByTagsIn(List tags, Pageable pageable);
diff --git a/src/main/java/com/sopromadze/blogapi/security/JwtAuthenticationFilter.java b/src/main/java/com/sopromadze/blogapi/security/JwtAuthenticationFilter.java
index 1a7181eb..fe7f8241 100644
--- a/src/main/java/com/sopromadze/blogapi/security/JwtAuthenticationFilter.java
+++ b/src/main/java/com/sopromadze/blogapi/security/JwtAuthenticationFilter.java
@@ -1,13 +1,16 @@
package com.sopromadze.blogapi.security;
import com.sopromadze.blogapi.service.CustomUserDetailsService;
+import com.sopromadze.blogapi.service.impl.CustomUserDetailsServiceImpl;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@@ -27,6 +30,9 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenProvider tokenProvider;
+ /*@Autowired
+ @Qualifier("customUserDetailsServiceImpl")
+ private CustomUserDetailsServiceImpl customUserDetailsService;*/
private final CustomUserDetailsService customUserDetailsService;
@Override
diff --git a/src/main/java/com/sopromadze/blogapi/service/AlbumService.java b/src/main/java/com/sopromadze/blogapi/service/AlbumService.java
index ef4a3621..45027d00 100644
--- a/src/main/java/com/sopromadze/blogapi/service/AlbumService.java
+++ b/src/main/java/com/sopromadze/blogapi/service/AlbumService.java
@@ -12,13 +12,13 @@ public interface AlbumService {
PagedResponse getAllAlbums(int page, int size);
- ResponseEntity addAlbum(AlbumRequest albumRequest, UserPrincipal currentUser);
+ Album addAlbum(AlbumRequest albumRequest, UserPrincipal currentUser);
- ResponseEntity getAlbum(Long id);
+ Album getAlbum(Long id);
- ResponseEntity updateAlbum(Long id, AlbumRequest newAlbum, UserPrincipal currentUser);
+ AlbumResponse updateAlbum(Long id, AlbumRequest newAlbum, UserPrincipal currentUser);
- ResponseEntity deleteAlbum(Long id, UserPrincipal currentUser);
+ ApiResponse deleteAlbum(Long id, UserPrincipal currentUser);
PagedResponse getUserAlbums(String username, int page, int size);
diff --git a/src/main/java/com/sopromadze/blogapi/service/CategoryService.java b/src/main/java/com/sopromadze/blogapi/service/CategoryService.java
index 65734a3e..a8d2f2b6 100644
--- a/src/main/java/com/sopromadze/blogapi/service/CategoryService.java
+++ b/src/main/java/com/sopromadze/blogapi/service/CategoryService.java
@@ -11,11 +11,11 @@ public interface CategoryService {
PagedResponse getAllCategories(int page, int size);
- ResponseEntity getCategory(Long id);
+ Category getCategory(Long id);
- ResponseEntity addCategory(Category category, UserPrincipal currentUser);
+ Category addCategory(Category category, UserPrincipal currentUser);
- ResponseEntity updateCategory(Long id, Category newCategory, UserPrincipal currentUser)
+ Category updateCategory(Long id, Category newCategory, UserPrincipal currentUser)
throws UnauthorizedException;
ResponseEntity deleteCategory(Long id, UserPrincipal currentUser) throws UnauthorizedException;
diff --git a/src/main/java/com/sopromadze/blogapi/service/CommentService.java b/src/main/java/com/sopromadze/blogapi/service/CommentService.java
index cdbc34de..32c151c3 100644
--- a/src/main/java/com/sopromadze/blogapi/service/CommentService.java
+++ b/src/main/java/com/sopromadze/blogapi/service/CommentService.java
@@ -5,6 +5,7 @@
import com.sopromadze.blogapi.payload.CommentRequest;
import com.sopromadze.blogapi.payload.PagedResponse;
import com.sopromadze.blogapi.security.UserPrincipal;
+import org.springframework.http.ResponseEntity;
public interface CommentService {
diff --git a/src/main/java/com/sopromadze/blogapi/service/PhotoService.java b/src/main/java/com/sopromadze/blogapi/service/PhotoService.java
index b59c767f..2afda361 100644
--- a/src/main/java/com/sopromadze/blogapi/service/PhotoService.java
+++ b/src/main/java/com/sopromadze/blogapi/service/PhotoService.java
@@ -1,20 +1,24 @@
package com.sopromadze.blogapi.service;
+import com.sopromadze.blogapi.model.Photo;
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.security.UserPrincipal;
+import org.springframework.http.ResponseEntity;
+
+import java.util.List;
public interface PhotoService {
PagedResponse getAllPhotos(int page, int size);
- PhotoResponse getPhoto(Long id);
+ Photo getPhoto(Long id);
- PhotoResponse updatePhoto(Long id, PhotoRequest photoRequest, UserPrincipal currentUser);
+ Photo updatePhoto(Long id, PhotoRequest photoRequest, UserPrincipal currentUser);
- PhotoResponse addPhoto(PhotoRequest photoRequest, UserPrincipal currentUser);
+ Photo addPhoto(PhotoRequest photoRequest, UserPrincipal currentUser);
ApiResponse deletePhoto(Long id, UserPrincipal currentUser);
diff --git a/src/main/java/com/sopromadze/blogapi/service/TagService.java b/src/main/java/com/sopromadze/blogapi/service/TagService.java
index db321cca..842fcab1 100644
--- a/src/main/java/com/sopromadze/blogapi/service/TagService.java
+++ b/src/main/java/com/sopromadze/blogapi/service/TagService.java
@@ -5,6 +5,7 @@
import com.sopromadze.blogapi.payload.PagedResponse;
import com.sopromadze.blogapi.security.UserPrincipal;
+
public interface TagService {
PagedResponse getAllTags(int page, int size);
diff --git a/src/main/java/com/sopromadze/blogapi/service/impl/AlbumServiceImpl.java b/src/main/java/com/sopromadze/blogapi/service/impl/AlbumServiceImpl.java
index 67a3630c..2ca15f24 100644
--- a/src/main/java/com/sopromadze/blogapi/service/impl/AlbumServiceImpl.java
+++ b/src/main/java/com/sopromadze/blogapi/service/impl/AlbumServiceImpl.java
@@ -41,7 +41,6 @@ public class AlbumServiceImpl implements AlbumService {
private static final String YOU_DON_T_HAVE_PERMISSION_TO_MAKE_THIS_OPERATION = "You don't have permission to make this operation";
-
private final AlbumRepository albumRepository;
private final UserRepository userRepository;
@@ -68,7 +67,7 @@ public PagedResponse getAllAlbums(int page, int size) {
}
@Override
- public ResponseEntity addAlbum(AlbumRequest albumRequest, UserPrincipal currentUser) {
+ public Album addAlbum(AlbumRequest albumRequest, UserPrincipal currentUser) {
User user = userRepository.getUser(currentUser);
Album album = new Album();
@@ -77,17 +76,19 @@ public ResponseEntity addAlbum(AlbumRequest albumRequest, UserPrincipal c
album.setUser(user);
Album newAlbum = albumRepository.save(album);
- return new ResponseEntity<>(newAlbum, HttpStatus.CREATED);
+
+ return album;
}
@Override
- public ResponseEntity getAlbum(Long id) {
+ public Album getAlbum(Long id) {
Album album = albumRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(ALBUM_STR, ID, id));
- return new ResponseEntity<>(album, HttpStatus.OK);
+
+ return album;
}
@Override
- public ResponseEntity updateAlbum(Long id, AlbumRequest newAlbum, UserPrincipal currentUser) {
+ public AlbumResponse updateAlbum(Long id, AlbumRequest newAlbum, UserPrincipal currentUser) {
Album album = albumRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(ALBUM_STR, ID, id));
User user = userRepository.getUser(currentUser);
if (album.getUser().getId().equals(user.getId()) || currentUser.getAuthorities()
@@ -99,20 +100,20 @@ public ResponseEntity updateAlbum(Long id, AlbumRequest newAlbum,
modelMapper.map(updatedAlbum, albumResponse);
- return new ResponseEntity<>(albumResponse, HttpStatus.OK);
+ return albumResponse;
}
throw new BlogapiException(HttpStatus.UNAUTHORIZED, YOU_DON_T_HAVE_PERMISSION_TO_MAKE_THIS_OPERATION);
}
@Override
- public ResponseEntity deleteAlbum(Long id, UserPrincipal currentUser) {
+ public ApiResponse deleteAlbum(Long id, UserPrincipal currentUser) {
Album album = albumRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(ALBUM_STR, ID, id));
User user = userRepository.getUser(currentUser);
if (album.getUser().getId().equals(user.getId()) || currentUser.getAuthorities()
.contains(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString()))) {
albumRepository.deleteById(id);
- return new ResponseEntity<>(new ApiResponse(Boolean.TRUE, "You successfully deleted album"), HttpStatus.OK);
+ return new ApiResponse(Boolean.TRUE, "You successfully deleted album");
}
throw new BlogapiException(HttpStatus.UNAUTHORIZED, YOU_DON_T_HAVE_PERMISSION_TO_MAKE_THIS_OPERATION);
diff --git a/src/main/java/com/sopromadze/blogapi/service/impl/CategoryServiceImpl.java b/src/main/java/com/sopromadze/blogapi/service/impl/CategoryServiceImpl.java
index b0130bea..21f4f48c 100644
--- a/src/main/java/com/sopromadze/blogapi/service/impl/CategoryServiceImpl.java
+++ b/src/main/java/com/sopromadze/blogapi/service/impl/CategoryServiceImpl.java
@@ -45,25 +45,25 @@ public PagedResponse getAllCategories(int page, int size) {
}
@Override
- public ResponseEntity getCategory(Long id) {
+ public Category getCategory(Long id) {
Category category = categoryRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Category", "id", id));
- return new ResponseEntity<>(category, HttpStatus.OK);
+ return category;
}
@Override
- public ResponseEntity addCategory(Category category, UserPrincipal currentUser) {
+ public Category addCategory(Category category, UserPrincipal currentUser) {
Category newCategory = categoryRepository.save(category);
- return new ResponseEntity<>(newCategory, HttpStatus.CREATED);
+ return newCategory;
}
@Override
- public ResponseEntity updateCategory(Long id, Category newCategory, UserPrincipal currentUser) {
+ public Category updateCategory(Long id, Category newCategory, UserPrincipal currentUser) {
Category category = categoryRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Category", "id", id));
if (category.getCreatedBy().equals(currentUser.getId()) || currentUser.getAuthorities()
.contains(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString()))) {
category.setName(newCategory.getName());
Category updatedCategory = categoryRepository.save(category);
- return new ResponseEntity<>(updatedCategory, HttpStatus.OK);
+ return category;
}
throw new UnauthorizedException("You don't have permission to edit this category");
diff --git a/src/main/java/com/sopromadze/blogapi/service/impl/CustomUserDetailsServiceImpl.java b/src/main/java/com/sopromadze/blogapi/service/impl/CustomUserDetailsServiceImpl.java
index 075287b4..64c1ec13 100644
--- a/src/main/java/com/sopromadze/blogapi/service/impl/CustomUserDetailsServiceImpl.java
+++ b/src/main/java/com/sopromadze/blogapi/service/impl/CustomUserDetailsServiceImpl.java
@@ -13,7 +13,7 @@
import javax.transaction.Transactional;
-@Service
+@Service("customUserDetailsServiceImpl")
@RequiredArgsConstructor
public class CustomUserDetailsServiceImpl implements UserDetailsService, CustomUserDetailsService {
diff --git a/src/main/java/com/sopromadze/blogapi/service/impl/PhotoServiceImpl.java b/src/main/java/com/sopromadze/blogapi/service/impl/PhotoServiceImpl.java
index fe9504e1..70ad070d 100644
--- a/src/main/java/com/sopromadze/blogapi/service/impl/PhotoServiceImpl.java
+++ b/src/main/java/com/sopromadze/blogapi/service/impl/PhotoServiceImpl.java
@@ -16,7 +16,6 @@
import com.sopromadze.blogapi.utils.AppConstants;
import com.sopromadze.blogapi.utils.AppUtils;
import lombok.RequiredArgsConstructor;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@@ -64,15 +63,14 @@ public PagedResponse getAllPhotos(int page, int size) {
}
@Override
- public PhotoResponse getPhoto(Long id) {
+ public Photo getPhoto(Long id) {
Photo photo = photoRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(PHOTO, ID, id));
- return new PhotoResponse(photo.getId(), photo.getTitle(), photo.getUrl(),
- photo.getThumbnailUrl(), photo.getAlbum().getId());
+ return photo;
}
@Override
- public PhotoResponse updatePhoto(Long id, PhotoRequest photoRequest, UserPrincipal currentUser) {
+ public Photo updatePhoto(Long id, PhotoRequest photoRequest, UserPrincipal currentUser) {
Album album = albumRepository.findById(photoRequest.getAlbumId())
.orElseThrow(() -> new ResourceNotFoundException(ALBUM, ID, photoRequest.getAlbumId()));
Photo photo = photoRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(PHOTO, ID, id));
@@ -82,8 +80,7 @@ public PhotoResponse updatePhoto(Long id, PhotoRequest photoRequest, UserPrincip
photo.setThumbnailUrl(photoRequest.getThumbnailUrl());
photo.setAlbum(album);
Photo updatedPhoto = photoRepository.save(photo);
- return new PhotoResponse(updatedPhoto.getId(), updatedPhoto.getTitle(),
- updatedPhoto.getUrl(), updatedPhoto.getThumbnailUrl(), updatedPhoto.getAlbum().getId());
+ return photo;
}
ApiResponse apiResponse = new ApiResponse(Boolean.FALSE, "You don't have permission to update this photo");
@@ -92,15 +89,14 @@ public PhotoResponse updatePhoto(Long id, PhotoRequest photoRequest, UserPrincip
}
@Override
- public PhotoResponse addPhoto(PhotoRequest photoRequest, UserPrincipal currentUser) {
+ public Photo addPhoto(PhotoRequest photoRequest, UserPrincipal currentUser) {
Album album = albumRepository.findById(photoRequest.getAlbumId())
.orElseThrow(() -> new ResourceNotFoundException(ALBUM, ID, photoRequest.getAlbumId()));
if (album.getUser().getId().equals(currentUser.getId())) {
Photo photo = new Photo(photoRequest.getTitle(), photoRequest.getUrl(), photoRequest.getThumbnailUrl(),
album);
Photo newPhoto = photoRepository.save(photo);
- return new PhotoResponse(newPhoto.getId(), newPhoto.getTitle(), newPhoto.getUrl(),
- newPhoto.getThumbnailUrl(), newPhoto.getAlbum().getId());
+ return photo;
}
ApiResponse apiResponse = new ApiResponse(Boolean.FALSE, "You don't have permission to add photo in this album");
diff --git a/src/main/java/com/sopromadze/blogapi/service/impl/PostServiceImpl.java b/src/main/java/com/sopromadze/blogapi/service/impl/PostServiceImpl.java
index 81045d47..0a091636 100644
--- a/src/main/java/com/sopromadze/blogapi/service/impl/PostServiceImpl.java
+++ b/src/main/java/com/sopromadze/blogapi/service/impl/PostServiceImpl.java
@@ -18,10 +18,10 @@
import com.sopromadze.blogapi.repository.UserRepository;
import com.sopromadze.blogapi.security.UserPrincipal;
import com.sopromadze.blogapi.service.PostService;
+
import com.sopromadze.blogapi.utils.AppConstants;
-import com.sopromadze.blogapi.utils.AppUtils;
import lombok.RequiredArgsConstructor;
-import org.springframework.beans.factory.annotation.Autowired;
+
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@@ -81,12 +81,12 @@ public PagedResponse getPostsByCreatedBy(String username, int page, int si
@Override
public PagedResponse getPostsByCategory(Long id, int page, int size) {
- AppUtils.validatePageNumberAndSize(page, size);
+ validatePageNumberAndSize(page, size);
Category category = categoryRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(CATEGORY, ID, id));
Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, CREATED_AT);
- Page posts = postRepository.findByCategory(category.getId(), pageable);
+ Page posts = postRepository.findByCategoryId(category.getId(), pageable);
List content = posts.getNumberOfElements() == 0 ? Collections.emptyList() : posts.getContent();
@@ -96,7 +96,7 @@ public PagedResponse getPostsByCategory(Long id, int page, int size) {
@Override
public PagedResponse getPostsByTag(Long id, int page, int size) {
- AppUtils.validatePageNumberAndSize(page, size);
+ validatePageNumberAndSize(page, size);
Tag tag = tagRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(TAG, ID, id));
@@ -188,7 +188,7 @@ public Post getPost(Long id) {
return postRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(POST, ID, id));
}
- private void validatePageNumberAndSize(int page, int size) {
+ private void validatePageNumberAndSize(int page, int size) {
if (page < 0) {
throw new BadRequestException("Page number cannot be less than zero.");
}
@@ -201,4 +201,5 @@ private void validatePageNumberAndSize(int page, int size) {
throw new BadRequestException("Page size must not be greater than " + AppConstants.MAX_PAGE_SIZE);
}
}
+
}
diff --git a/src/main/resources/_application.properties b/src/main/resources/_application.properties
index d7d7b14c..1302b16e 100644
--- a/src/main/resources/_application.properties
+++ b/src/main/resources/_application.properties
@@ -10,3 +10,5 @@ app.jwtExpirationInMs=3600000
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
spring.jackson.time-zone=UTC
cors.allowedOrings=*
+
+spring.main.allow-bean-definition-overriding=true
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index c07f07f4..5cd3e79f 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -1,4 +1,8 @@
spring:
profiles:
- active: "dev"
\ No newline at end of file
+ active: "dev"
+
+
+ main:
+ allow-bean-definition-overriding: true
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/controller/AlbumControllerTest.java b/src/test/java/com/sopromadze/blogapi/controller/AlbumControllerTest.java
new file mode 100644
index 00000000..15d9850b
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/controller/AlbumControllerTest.java
@@ -0,0 +1,208 @@
+package com.sopromadze.blogapi.controller;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sopromadze.blogapi.model.Album;
+import com.sopromadze.blogapi.model.Photo;
+import com.sopromadze.blogapi.model.role.RoleName;
+import com.sopromadze.blogapi.payload.AlbumResponse;
+import com.sopromadze.blogapi.payload.ApiResponse;
+import com.sopromadze.blogapi.payload.PagedResponse;
+import com.sopromadze.blogapi.payload.PhotoResponse;
+import com.sopromadze.blogapi.payload.request.AlbumRequest;
+import com.sopromadze.blogapi.security.UserPrincipal;
+import com.sopromadze.blogapi.service.AlbumService;
+import com.sopromadze.blogapi.service.PhotoService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import com.sopromadze.blogapi.model.user.User;
+
+import org.springframework.security.test.context.support.WithUserDetails;
+import org.springframework.test.web.servlet.MockMvc;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {SpringSecurityTestWebConfig.class})
+@AutoConfigureMockMvc
+class AlbumControllerTest {
+
+ @MockBean
+ private AlbumService albumService;
+
+ @MockBean
+ private PhotoService photoService;
+
+ @InjectMocks
+ private AlbumController albumController;
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Autowired
+ private ObjectMapper objectMapper;
+
+ private static User usuario;
+ private static Photo photo1, photo2;
+ private static List photos;
+ private static Album album;
+ private static AlbumRequest albumRequest;
+ private static UserPrincipal user;
+ private static AlbumResponse albumResponse;
+ private static PhotoResponse photoResponse;
+
+ @BeforeEach
+ void initTest(){
+
+ user = new UserPrincipal(
+ 123L,
+ "Paco",
+ "Lopez",
+ "pacols",
+ "pacols@gmail.com",
+ "123",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+
+ usuario = new User();
+ usuario.setId(9652L);
+ usuario.setUsername("pacols");
+ usuario.setEmail("pacosl@gmail.com");
+
+
+ photo1 = new Photo();
+ photo1.setTitle("Foto1");
+ photo1.setId(1L);
+ photo1.setUrl("www.photo/foto.1.jpg");
+
+ photo2 = new Photo();
+ photo1.setTitle("Foto2");
+ photo1.setId(1L);
+ photo1.setUrl("www.photo/foto.2.jpg");
+
+ photos = new ArrayList();
+ photos.add(photo1);
+ photos.add(photo2);
+
+ photoResponse = new PhotoResponse(2L,"Photo", "www.photo.com", "www.img.com", 95L);
+
+
+ album = new Album();
+ album.setId(95L);
+ album.setTitle("Album 1");
+ album.setPhoto(photos);
+ album.setUser(usuario);
+
+ albumResponse = new AlbumResponse();
+ albumResponse.setId(95L);
+ albumResponse.setTitle("Album 1");
+ albumResponse.setPhoto(photos);
+ albumResponse.setUser(usuario);
+
+ albumRequest = new AlbumRequest();
+ albumRequest.setId(95L);
+ albumRequest.setTitle("Album 1");
+ albumRequest.setPhoto(photos);
+
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void addAlbum_Success() throws Exception{
+ when(albumService.addAlbum(albumRequest, user)).thenReturn(album);
+
+ mockMvc.perform(
+ post("/api/albums")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(album)))
+ .andExpect(status().isCreated());
+ }
+
+ @Test
+ @WithUserDetails("admin")
+ void addAlbum_Forbiden() throws Exception{
+ mockMvc.perform(
+ post("/api/albums")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(album)))
+ .andExpect(status().isForbidden());
+ }
+
+ @Test
+ void getAlbum_Success() throws Exception{
+ when(albumService.getAlbum(95L)).thenReturn(album);
+
+ mockMvc.perform(
+ get("/api/albums/{id}", 95L)
+ .contentType("application/json"))
+ .andExpect(jsonPath("$.id").value(95L))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ @WithUserDetails("admin")
+ void updateAlbum_Success() throws Exception{
+ when(albumService.updateAlbum(5L,albumRequest, user)).thenReturn(albumResponse);
+
+ mockMvc.perform(
+ put("/api/albums/{id}",95L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(albumRequest)))
+ .andExpect(status().isCreated());
+ }
+
+ @Test
+ void updateAlbum_Unauthorized() throws Exception{
+ when(albumService.updateAlbum(5L,albumRequest, user)).thenReturn(albumResponse);
+
+ mockMvc.perform(
+ put("/api/albums/{id}",95L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(albumRequest)))
+ .andExpect(status().isUnauthorized());
+ }
+
+ @Test
+ @WithUserDetails("admin")
+ void deleteAlbum_Success() throws Exception{
+ ApiResponse apiResponse = new ApiResponse(true, "Se ha borrado el album");
+ when(albumService.deleteAlbum(2L, user)).thenReturn(apiResponse);
+
+ mockMvc.perform(
+ delete("/api/albums/{id}", 95L))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ void deleteAlbum_Unauthorized() throws Exception{
+ ApiResponse apiResponse = new ApiResponse(true, "Se ha borrado el album");
+ when(albumService.deleteAlbum(2L, user)).thenReturn(apiResponse);
+
+ mockMvc.perform(
+ delete("/api/albums/{id}", 95L))
+ .andExpect(status().isUnauthorized());
+ }
+
+
+ @Test
+ void getAllPhotosByAlbum_Success() throws Exception{
+ PagedResponse response =
+ new PagedResponse(List.of(photoResponse),1,1,1,1, true);
+ when(photoService.getAllPhotosByAlbum(95L,1,1)).thenReturn(response);
+
+ mockMvc.perform(
+ get("/api/albums/{id}/photos",95L)
+ .param("page", "1")
+ .param("size", "1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.content[0].id").value(2));
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/controller/CategoryControllerTest.java b/src/test/java/com/sopromadze/blogapi/controller/CategoryControllerTest.java
new file mode 100644
index 00000000..1c21cc2a
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/controller/CategoryControllerTest.java
@@ -0,0 +1,141 @@
+package com.sopromadze.blogapi.controller;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sopromadze.blogapi.model.Category;
+import com.sopromadze.blogapi.model.role.RoleName;
+import com.sopromadze.blogapi.payload.ApiResponse;
+import com.sopromadze.blogapi.payload.PagedResponse;
+import com.sopromadze.blogapi.security.UserPrincipal;
+import com.sopromadze.blogapi.service.impl.CategoryServiceImpl;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.test.context.support.WithUserDetails;
+import org.springframework.test.web.servlet.MockMvc;
+
+import java.util.List;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = {SpringSecurityTestWebConfig.class})
+@AutoConfigureMockMvc
+class CategoryControllerTest {
+
+ @MockBean
+ CategoryServiceImpl categoryService;
+
+ @InjectMocks
+ CategoryController categoryController;
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Autowired
+ private ObjectMapper objectMapper;
+
+ static Long CATEGORY_ID=1L;
+ static Category category;
+ static UserPrincipal user;
+ static ApiResponse apiResponse;
+
+ @BeforeEach
+ void init(){
+ apiResponse=new ApiResponse(true,"You successfully deleted category");
+ user = new UserPrincipal(1L,"user", "user","user","user@gmail.com", "user", List.of(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+ category=new Category();category.setId(1L); category.setName("Viaje");
+ }
+
+
+ @Test
+ void getAllCategories_Success() throws Exception{
+ PagedResponse pr=new PagedResponse(List.of(category),1,1,1,1,true);
+ when(categoryService.getAllCategories(anyInt(),anyInt())).thenReturn(pr);
+
+ mockMvc.perform(get("/api/categories")
+ .param("page","1")
+ .param("size","1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.content[0].id").value(1));
+ }
+
+
+ @Test
+ @WithUserDetails("user")
+ void addCategory_Success() throws Exception {
+ when(categoryService.addCategory(any(Category.class),any(UserPrincipal.class))).thenReturn(category);
+ mockMvc.perform(
+ post("/api/categories")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(category)))
+ //.andExpect(jsonPath("$.id").value(1L))
+ .andExpect(status().isCreated());
+ }
+
+ @Test
+ @WithUserDetails("admin")
+ void addCategory_Forbidden() throws Exception {
+ mockMvc.perform(
+ post("/api/categories")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsBytes(category)))
+ .andExpect(status().isForbidden());
+ }
+
+ @Test
+ void addCategory_UnAuthorized() throws Exception {
+ mockMvc.perform(
+ post("/api/categories")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsBytes(category)))
+ .andExpect(status().isUnauthorized());
+ }
+
+ @Test
+ void getCategory_Success() throws Exception{
+ when(categoryService.getCategory(anyLong())).thenReturn(category);
+ mockMvc.perform(get("/api/categories/{id}",CATEGORY_ID))
+ .andExpect(jsonPath("$.id").value(CATEGORY_ID))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ @WithUserDetails("admin")
+ void updateCategory_Success() throws Exception{
+ when(categoryService.updateCategory(anyLong(),any(Category.class),any(UserPrincipal.class))).thenReturn(category);
+
+ mockMvc.perform(put("/api/categories/{id}",CATEGORY_ID)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(category)))
+ .andExpect(status().isOk());
+ }
+
+
+ @Test
+ @WithUserDetails("admin")
+ void deleteCategory_Success() throws Exception{
+
+ when(categoryService.deleteCategory(anyLong(),any(UserPrincipal.class))).thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK));
+
+ mockMvc.perform(delete("/api/categories/{id}",CATEGORY_ID) )
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ void deleteCategory_UnAuthorized() throws Exception{
+
+ mockMvc.perform(delete("/api/categories/{id}",CATEGORY_ID))
+ .andExpect(status().isUnauthorized());
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/controller/CommentControllerTest.java b/src/test/java/com/sopromadze/blogapi/controller/CommentControllerTest.java
new file mode 100644
index 00000000..92280291
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/controller/CommentControllerTest.java
@@ -0,0 +1,209 @@
+package com.sopromadze.blogapi.controller;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sopromadze.blogapi.exception.BadRequestException;
+import com.sopromadze.blogapi.exception.ResourceNotFoundException;
+import com.sopromadze.blogapi.model.Comment;
+import com.sopromadze.blogapi.model.Post;
+import com.sopromadze.blogapi.model.Tag;
+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.CommentRequest;
+import com.sopromadze.blogapi.payload.PagedResponse;
+import com.sopromadze.blogapi.security.UserPrincipal;
+import com.sopromadze.blogapi.service.CommentService;
+import javassist.NotFoundException;
+import lombok.extern.java.Log;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.security.test.context.support.WithUserDetails;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.Optional;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+import static org.hamcrest.Matchers.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+@Log
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {SpringSecurityTestWebConfig.class})
+@AutoConfigureMockMvc
+class CommentControllerTest {
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Autowired
+ private ObjectMapper objectMapper;
+
+ @MockBean
+ private CommentService service;
+
+
+ @Test
+ void getAllComments_success() throws Exception {
+
+ Comment c = new Comment();
+ c.setName("comentario");
+ c.setBody("bodybodybodybody");
+ c.setEmail("email");
+ c.setId(1L);
+
+ PagedResponse comentarios = new PagedResponse();
+ comentarios.setContent(List.of(c));
+
+ when(service.getAllComments(any(Long.class), any(Integer.class), any(Integer.class))).thenReturn(comentarios);
+
+ MvcResult result = mockMvc.perform(get("/api/posts/{postId}/comments", 1L))
+ .andExpect(jsonPath("$.content[0].id", is(1)))
+ .andExpect(jsonPath("$.content", hasSize(1)))
+ .andReturn();
+
+ log.info(result.getResponse().getContentAsString());
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void addComment_success() throws Exception{
+
+ Comment c = new Comment();
+ c.setName("comentario");
+ c.setBody("bodybodybodybody");
+ c.setEmail("email");
+ c.setId(1L);
+
+ PagedResponse comentarios = new PagedResponse();
+ comentarios.setContent(List.of(c));
+
+ when(service.addComment(any(CommentRequest.class), any(Long.class), any(UserPrincipal.class))).thenReturn(c);
+
+ mockMvc.perform(post("/api/posts/{postId}/comments", 1L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(c)))
+ //.andExpect(jsonPath("$.id").value(1))
+ .andExpect(status().isCreated());
+ }
+
+ @Test
+ void addComment_unauthorized() throws Exception{
+
+ mockMvc.perform(post("/api/posts/{postId}/comments", 1L))
+ .andExpect(status().isUnauthorized())
+ .andReturn();
+ }
+
+ @Test
+ void getComment_success() throws Exception{
+
+ Comment c = new Comment();
+ c.setName("comentario");
+ c.setBody("bodybodybodybody");
+ c.setEmail("email");
+ c.setId(1L);
+
+ when(service.getComment(any(Long.class), any(Long.class))).thenReturn(c);
+
+ MvcResult result = mockMvc.perform(get("/api/posts/{postId}/comments/{id}", 1L, 1L))
+ .andExpect(jsonPath("$.id", is(1)))
+ .andReturn();
+
+ log.info(result.getResponse().getContentAsString());
+ }
+
+ @Test
+ void getComment_NotFound() throws Exception{
+
+ when(service.getComment(any(Long.class), any(Long.class))).thenThrow(ResourceNotFoundException.class);
+
+ MvcResult result = mockMvc.perform(get("/api/posts/{postId}/comments/{id}", 1L, 1L))
+ .andExpect(status().isNotFound())
+ .andReturn();
+
+ log.info(result.getResponse().getContentAsString());
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void updateComment() throws Exception{
+
+ Comment c = new Comment();
+ c.setName("comentario");
+ c.setBody("bodybodybodybody");
+ c.setEmail("email");
+ c.setId(1L);
+
+ PagedResponse comentarios = new PagedResponse();
+ comentarios.setContent(List.of(c));
+
+ when(service.updateComment(any(Long.class), any(Long.class), any(CommentRequest.class), any(UserPrincipal.class))).thenReturn(c);
+
+ mockMvc.perform(put("/api/posts/{postId}/comments/{id}", 1L, 1L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(c)))
+ //.andExpect(jsonPath("$.id").value(1))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ void updateComment_unauthorized() throws Exception{
+
+ mockMvc.perform(put("/api/posts/{postId}/comments/{id}", 1L, 1L))
+ .andExpect(status().isUnauthorized())
+ .andReturn();
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void updateComment_badrequest() throws Exception{
+
+ Comment c = new Comment();
+ c.setName("comentario");
+ c.setBody("bodybodybodybody");
+ c.setEmail("email");
+ c.setId(1L);
+
+ when(service.updateComment(any(Long.class), any(Long.class), any(CommentRequest.class), any(UserPrincipal.class))).thenThrow(BadRequestException.class);
+
+ MvcResult result = mockMvc.perform(put("/api/posts/{postId}/comments/{id}", 1L, 1L)
+ .contentType("application/json"))
+ .andExpect(status().isBadRequest())
+ .andReturn();
+
+ log.info(result.getResponse().getContentAsString());
+
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void deleteComment_success() throws Exception {
+
+ Post p = new Post();
+ p.setId(1L);
+
+ Comment c = new Comment();
+ c.setName("comentario");
+ c.setBody("bodybodybodybody");
+ c.setEmail("email");
+ c.setId(1L);
+ c.setPost(p);
+
+ when(service.deleteComment(any(Long.class), any(Long.class), any(UserPrincipal.class))).thenReturn(new ApiResponse(Boolean.TRUE, "You successfully deleted comment"));
+
+ mockMvc.perform(delete("/api/posts/{postId}/comments/{id}", 1L, 1L)
+ .contentType("application/json"))
+ .andExpect(status().isOk());
+
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/controller/PhotoControllerTest.java b/src/test/java/com/sopromadze/blogapi/controller/PhotoControllerTest.java
new file mode 100644
index 00000000..4873f7e9
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/controller/PhotoControllerTest.java
@@ -0,0 +1,413 @@
+package com.sopromadze.blogapi.controller;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sopromadze.blogapi.exception.ResourceNotFoundException;
+import com.sopromadze.blogapi.model.Album;
+import com.sopromadze.blogapi.model.Photo;
+import com.sopromadze.blogapi.model.role.RoleName;
+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.security.UserPrincipal;
+import com.sopromadze.blogapi.service.PhotoService;
+import lombok.extern.java.Log;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.test.context.support.WithUserDetails;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+import org.springframework.test.web.servlet.ResultMatcher;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+
+import java.util.Collections;
+import java.util.List;
+
+import static com.sopromadze.blogapi.utils.AppConstants.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+
+@Log
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {SpringSecurityTestWebConfig.class})
+@AutoConfigureMockMvc
+class PhotoControllerTest {
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Autowired
+ private ObjectMapper objectMapper;
+
+ @MockBean
+ private PhotoService photoService;
+
+ @Test
+ void getAllPhotosSuccessTest() throws Exception {
+
+ //Instanciamos todo lo necesario
+
+ PhotoResponse photo1 = new PhotoResponse(
+ 1L,
+ "fotito 1",
+ "https://google.com",
+ "otra url",
+ 1L
+ );
+
+ PhotoResponse photo2 = new PhotoResponse(
+ 2L,
+ "fotito 2",
+ "https://google.com",
+ "otra url",
+ 1L
+ );
+
+ PhotoResponse photo3 = new PhotoResponse(
+ 3L,
+ "fotito 3",
+ "https://google.com",
+ "otra url",
+ 1L
+ );
+
+
+ List photos = List.of(photo1, photo2, photo3);
+ PagedResponse pagedResponse = new PagedResponse<>(photos, 1, 1, 3, 1, true);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(photoService.getAllPhotos(1, 1)).thenReturn(pagedResponse);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(get("/api/photos")
+ .param("page", "1")
+ .param("size", "1"))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ String result = mvcResult.getResponse().getContentAsString();
+
+ Assertions.assertThat(result).isEqualToIgnoringWhitespace(objectMapper.writeValueAsString(pagedResponse));
+
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void addPhotoSuccessTest() throws Exception {
+
+ //Instanciamos lo necesario
+
+ PhotoRequest request = new PhotoRequest();
+ request.setTitle("Photo 1");
+ request.setUrl("https://www.google.com");
+ request.setThumbnailUrl("https://www.google.com");
+ request.setAlbumId(1L);
+
+ UserPrincipal user = new UserPrincipal(1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+
+ Album album = new Album();
+ album.setTitle("Vacaciones");
+
+ Photo photo = new Photo(
+ "Photo 1",
+ "https://www.google.com",
+ "https://www.google.com",
+ album
+ );
+ photo.setId(1L);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(photoService.addPhoto(request, user)).thenReturn(photo);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(post("/api/photos")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(request)))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void addPhotoBadRequestTest() throws Exception {
+
+ //Instanciamos lo necesario
+
+ PhotoRequest request = new PhotoRequest();
+ request.setUrl("https://www.google.com");
+ request.setThumbnailUrl("https://www.google.com");
+ request.setAlbumId(1L);
+
+ Album album = new Album();
+ album.setTitle("Vacaciones");
+
+ Photo photo = new Photo(
+ "Photo 1",
+ "https://www.google.com",
+ "https://www.google.com",
+ album
+ );
+ photo.setId(1L);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(photoService.addPhoto(any(PhotoRequest.class), any(UserPrincipal.class))).thenReturn(photo);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(post("/api/photos")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(request)))
+ .andExpect(status().isBadRequest())
+ .andReturn();
+
+ }
+
+ @Test
+ void addPhotoUnauthorizedExceptionTest() throws Exception {
+
+ //Instanciamos lo necesario
+
+ PhotoRequest request = new PhotoRequest();
+ request.setTitle("Photo 1");
+ request.setUrl("https://www.google.com");
+ request.setThumbnailUrl("https://www.google.com");
+ request.setAlbumId(1L);
+
+ UserPrincipal user = new UserPrincipal(1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+
+ Album album = new Album();
+ album.setTitle("Vacaciones");
+
+ Photo photo = new Photo(
+ "Photo 1",
+ "https://www.google.com",
+ "https://www.google.com",
+ album
+ );
+ photo.setId(1L);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(photoService.addPhoto(request, user)).thenReturn(photo);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(post("/api/photos")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(request)))
+ .andExpect(status().isUnauthorized())
+ .andReturn();
+
+ }
+
+ @Test
+ void getPhotoSuccessTest() throws Exception {
+
+ //Instanciamos lo necesario
+
+ Album album = new Album();
+ album.setTitle("Vacaciones");
+
+ Photo photo = new Photo("Photo 1",
+ "https://www.google.com",
+ "https://www.google.com",
+ album
+ );
+ photo.setId(1L);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(photoService.getPhoto(1L)).thenReturn(photo);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(get("/api/photos/{id}", 1L))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ void getPhotoResourceNotFoundExceptionTest() throws Exception {
+
+ //Mockeamos lo necesario
+
+ Mockito.when(photoService.getPhoto(1L)).thenThrow(new ResourceNotFoundException(PHOTO, ID, 1L));
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(get("/api/photos/{id}", 1L))
+ .andExpect(status().isNotFound())
+ .andReturn();
+
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void updatePhotoSuccessTest() throws Exception {
+
+ //Instanciamos lo necesario
+
+ Photo photo = new Photo();
+
+ PhotoRequest request = new PhotoRequest();
+ request.setTitle("Photo 1");
+ request.setUrl("https://www.google.com");
+ request.setThumbnailUrl("https://www.google.com");
+ request.setAlbumId(1L);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(photoService.updatePhoto(any(Long.class), any(PhotoRequest.class), any(UserPrincipal.class))).thenReturn(photo);
+
+ //Implementamos los metodos
+
+ MvcResult mvcResult = mockMvc.perform(put("/api/photos/{id}", 1L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(request)))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ void updatePhotoUnauthorizedTest() throws Exception {
+
+ //Instanciamos lo necesario
+
+ PhotoRequest request = new PhotoRequest();
+ request.setTitle("Photo 1");
+ request.setUrl("https://www.google.com");
+ request.setThumbnailUrl("https://www.google.com");
+ request.setAlbumId(1L);
+
+ //Implementamos los metodos
+
+ MvcResult mvcResult = mockMvc.perform(put("/api/photos/{id}", 1L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(request)))
+ .andExpect(status().isUnauthorized())
+ .andReturn();
+
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void updatePhotoBadRequetsTest() throws Exception {
+
+ //Instanciamos lo necesario
+
+ PhotoRequest request = new PhotoRequest();
+ request.setUrl("https://www.google.com");
+ request.setThumbnailUrl("https://www.google.com");
+ request.setAlbumId(1L);
+
+ //Implementamos los metodos
+
+ MvcResult mvcResult = mockMvc.perform(put("/api/photos/{id}", 1L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(request)))
+ .andExpect(status().isBadRequest())
+ .andReturn();
+
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void updatePhotoResourceNotFoundExceptionTest() throws Exception {
+
+ //Instanciamos lo necesario
+
+ PhotoRequest request = new PhotoRequest();
+ request.setTitle("Photo 1");
+ request.setUrl("https://www.google.com");
+ request.setThumbnailUrl("https://www.google.com");
+ request.setAlbumId(2L);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(photoService.updatePhoto(any(Long.class), any(PhotoRequest.class), any(UserPrincipal.class))).thenThrow(new ResourceNotFoundException(PHOTO, ID, 1L));
+
+ //Implementamos los metodos
+
+ MvcResult mvcResult = mockMvc.perform(put("/api/photos/{id}", 1L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(request)))
+ .andExpect(status().isNotFound())
+ .andReturn();
+
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void deletePhotoSuccessTest() throws Exception {
+
+ //Instanciamos lo necesario
+
+ ApiResponse response = new ApiResponse(Boolean.TRUE, "Photo deleted successfully");
+
+ //Mockeamos lo necesario
+
+ Mockito.when(photoService.deletePhoto(any(Long.class), any(UserPrincipal.class))).thenReturn(response);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(delete("/api/photos/{id}", 1L))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ void deletePhotoUnauthorizedTest() throws Exception {
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(delete("/api/photos/{id}", 1L))
+ .andExpect(status().isUnauthorized())
+ .andReturn();
+
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void deletePhotoResourceNotFoundExceptionTest() throws Exception {
+
+ //Mockeamos lo necesario
+
+ Mockito.when(photoService.deletePhoto(any(Long.class), any(UserPrincipal.class))).thenThrow(new ResourceNotFoundException(PHOTO, ID, 1L));
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(delete("/api/photos/{id}", 1L))
+ .andExpect(status().isNotFound())
+ .andReturn();
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/controller/PostControllerTest.java b/src/test/java/com/sopromadze/blogapi/controller/PostControllerTest.java
new file mode 100644
index 00000000..9bd12b7a
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/controller/PostControllerTest.java
@@ -0,0 +1,203 @@
+package com.sopromadze.blogapi.controller;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sopromadze.blogapi.model.Category;
+import com.sopromadze.blogapi.model.Post;
+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.payload.PostRequest;
+import com.sopromadze.blogapi.payload.PostResponse;
+import com.sopromadze.blogapi.security.UserPrincipal;
+import com.sopromadze.blogapi.service.PostService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.test.context.support.WithUserDetails;
+import org.springframework.test.web.servlet.MockMvc;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+
+import static org.mockito.Mockito.when;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {SpringSecurityTestWebConfig.class})
+@AutoConfigureMockMvc
+class PostControllerTest {
+
+ @MockBean
+ private PostService postService;
+
+ @InjectMocks
+ private PostController postController;
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Autowired
+ private ObjectMapper objectMapper;
+
+ private static Post post;
+ private static Category category;
+ private static Tag tag;
+ private static PagedResponse pagedResponse;
+ private static UserPrincipal userPrincipal;
+ private static PostRequest postRequest;
+ private static PostResponse postResponse;
+ private static ApiResponse apiResponse;
+
+ @BeforeEach
+ void setUp() {
+
+ apiResponse=new ApiResponse(true,"Se ha borrado el post");
+
+ userPrincipal = new UserPrincipal(4L, "Pepe", "Palomo",
+ "pepepalomo", "pepepalomo@gmail.com", "1234",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+
+ category = new Category();
+ category.setId(2L);
+ category.setCreatedBy(4L);
+ category.setName("Categoria1");
+
+ postRequest = new PostRequest();
+ postRequest.setCategoryId(2L);
+ postRequest.setBody("BodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBody");
+ postRequest.setTitle("PostPostPostPost");
+
+ postResponse = new PostResponse();
+ postResponse.setCategory("Categoria1");
+ postResponse.setBody("BodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBodyBody");
+ postResponse.setTitle("PostPostPostPost");
+
+ tag = new Tag();
+ tag.setId(3L);
+ tag.setName("Tag1");
+
+ post = new Post();
+ post.setId(1L);
+ post.setCategory(category);
+ post.setTags(List.of(tag));
+ post.setCreatedAt(Instant.now());
+ post.setUpdatedAt(Instant.now());
+
+ pagedResponse = new PagedResponse(List.of(post),1,1,1,1,true);
+ }
+
+ @Test
+ void getAllPosts_Success() throws Exception{
+
+ when(postService.getAllPosts(1,1)).thenReturn(pagedResponse);
+
+ mockMvc.perform(
+ get("/api/posts")
+ .param("page","1")
+ .param("size","1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.content[0].id").value(1));
+ }
+
+ @Test
+ void getPostsByCategory_Success() throws Exception{
+ when(postService.getPostsByCategory(2L,1,1)).thenReturn(pagedResponse);
+
+ mockMvc.perform(
+ get("/api/posts/category/{id}", 2L)
+ .param("page","1")
+ .param("size","1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.content[0].id").value(1));
+ }
+
+ @Test
+ void getPostsByTag_Success() throws Exception{
+ when(postService.getPostsByTag(3L,1,1)).thenReturn(pagedResponse);
+
+ mockMvc.perform(
+ get("/api/posts/tag/{id}", 3L)
+ .param("page","1")
+ .param("size","1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.content[0].id").value(1));
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void addPost_Success() throws Exception{
+ when(postService.addPost(postRequest,userPrincipal)).thenReturn(postResponse);
+
+ mockMvc.perform(
+ post("/api/posts")
+ .contentType("application/json")
+ //.content(objectMapper.writeValueAsString(postResponse)))
+ .content(objectMapper.writeValueAsString(postRequest)))
+ .andExpect(status().isCreated());
+ }
+
+ @Test
+ void addPost_Unauthorized() throws Exception{
+ mockMvc.perform(
+ post("/api/posts")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(postResponse)))
+ .andExpect(status().isUnauthorized());
+ }
+
+ @Test
+ void getPost_Success() throws Exception {
+ when(postService.getPost(1L)).thenReturn(post);
+
+ mockMvc.perform(
+ get("/api/posts/{id}",1L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(post)))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ @WithUserDetails("admin")
+ void updatePost_Success() throws Exception {
+ when(postService.updatePost(1L,postRequest,userPrincipal)).thenReturn(post);
+
+ mockMvc.perform(
+ put("/api/albums/{id}",1L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(post)))
+ .andExpect(status().isCreated());
+ }
+
+ @Test
+ void updatePost_Unauthorized() throws Exception {
+ mockMvc.perform(
+ put("/api/albums/{id}",1L)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(post)))
+ .andExpect(status().isUnauthorized());
+ }
+
+ @Test
+ @WithUserDetails("admin")
+ void deletePost_Success() throws Exception {
+ when(postService.deletePost(1L, userPrincipal)).thenReturn(apiResponse);
+
+ mockMvc.perform(delete("/api/albums/{id}",1L) )
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ void deletePost_Unauthorized() throws Exception {
+ mockMvc.perform(delete("/api/albums/{id}",1L) )
+ .andExpect(status().isUnauthorized());
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/controller/SpringSecurityTestWebConfig.java b/src/test/java/com/sopromadze/blogapi/controller/SpringSecurityTestWebConfig.java
new file mode 100644
index 00000000..11fc87a1
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/controller/SpringSecurityTestWebConfig.java
@@ -0,0 +1,35 @@
+package com.sopromadze.blogapi.controller;
+
+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.security.UserPrincipal;
+import com.sopromadze.blogapi.service.CustomUserDetailsService;
+import com.sopromadze.blogapi.service.impl.CustomUserDetailsServiceImpl;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Primary;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.security.provisioning.InMemoryUserDetailsManager;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+@TestConfiguration
+public class SpringSecurityTestWebConfig {
+
+ @Bean("CustomUserDetailsServiceImpl")
+ @Primary
+ public UserDetailsService userDetailsService() {
+
+ UserPrincipal user = new UserPrincipal(1L,"user", "user","user","user@gmail.com", "user", Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+ UserPrincipal admin = new UserPrincipal(1L,"admin", "admin","admin","admin@gmail.com", "admin", Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())));
+
+ return new InMemoryUserDetailsManager(List.of(admin,user));
+ }
+}
diff --git a/src/test/java/com/sopromadze/blogapi/controller/TagControllerTest.java b/src/test/java/com/sopromadze/blogapi/controller/TagControllerTest.java
new file mode 100644
index 00000000..5b5e6d06
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/controller/TagControllerTest.java
@@ -0,0 +1,140 @@
+package com.sopromadze.blogapi.controller;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sopromadze.blogapi.model.Post;
+import com.sopromadze.blogapi.model.Tag;
+import com.sopromadze.blogapi.payload.ApiResponse;
+import com.sopromadze.blogapi.payload.PagedResponse;
+import com.sopromadze.blogapi.security.UserPrincipal;
+import com.sopromadze.blogapi.service.TagService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.data.domain.*;
+import org.springframework.security.test.context.support.WithUserDetails;
+import org.springframework.test.web.servlet.MockMvc;
+
+import java.util.List;
+
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = {SpringSecurityTestWebConfig.class})
+@AutoConfigureMockMvc
+class TagControllerTest {
+
+ @MockBean
+ TagService tagService;
+
+ @InjectMocks
+ TagController tagController;
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Autowired
+ private ObjectMapper objectMapper;
+
+ static int ONE=1;
+ static Long ONE_ID=1L;
+ static Page page;
+ static Pageable pageable;
+ static Tag tag;
+ static PagedResponse pagedResponse;
+
+ @BeforeEach
+ void init (){
+ tag=new Tag(); tag.setId(ONE_ID); tag.setName("MegaTag"); tag.setPosts(List.of(new Post()));
+ pageable= PageRequest.of(ONE, ONE, Sort.Direction.DESC,"a");
+ page=new PageImpl(List.of(tag),pageable,ONE);
+ pagedResponse=new PagedResponse(); pagedResponse.setPage(ONE);pagedResponse.setContent(List.of(tag));pagedResponse.setLast(true);pagedResponse.setTotalPages(ONE);pagedResponse.setTotalElements(1);
+ }
+
+ @Test
+ void getAllTags_Success () throws Exception{
+ when(tagService.getAllTags(ONE,ONE)).thenReturn(pagedResponse);
+
+ mockMvc.perform(get("/api/tags")
+ .param("page","1")
+ .param("size","1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.content[0].id").value(ONE_ID))
+ .andExpect(jsonPath("$.content[0].name").value("MegaTag"));
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void addTag_Success () throws Exception {
+ when(tagService.addTag(any(Tag.class),any(UserPrincipal.class))).thenReturn(tag);
+
+ mockMvc.perform(post("/api/tags")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(tag)))
+ .andExpect(status().isCreated());
+ }
+
+ @Test
+ @WithUserDetails("admin")
+ void addTag_Forbidden() throws Exception {
+ mockMvc.perform(post("/api/tags")
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(tag)))
+ .andExpect(status().isForbidden());
+ }
+
+ @Test
+ void getTag_Success() throws Exception {
+ when(tagService.getTag(anyLong())).thenReturn(tag);
+
+ mockMvc.perform(get("/api/tags/{id}",ONE_ID))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.id").value(ONE_ID))
+ .andExpect(jsonPath("$.name").value("MegaTag"));
+ }
+
+ @Test
+ @WithUserDetails("admin")
+ void updateTag_Success () throws Exception{
+ when(tagService.updateTag(anyLong(),any(Tag.class),any(UserPrincipal.class))).thenReturn(tag);
+
+ mockMvc.perform(put("/api/tags/{id}",ONE_ID)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(tag)))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ void updateTag_UnAuthorized () throws Exception{
+ mockMvc.perform(put("/api/tags/{id}",ONE_ID)
+ .contentType("application/json")
+ .content(objectMapper.writeValueAsString(tag)))
+ .andExpect(status().isUnauthorized());
+ }
+
+ @Test
+ @WithUserDetails("user")
+ void deleteTag_Success () throws Exception{
+ ApiResponse apiResponse=new ApiResponse(); apiResponse.setMessage("Deleted");
+ when(tagService.deleteTag(anyLong(),any(UserPrincipal.class))).thenReturn(apiResponse);
+
+ mockMvc.perform(delete("/api/tags/{id}",ONE_ID))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ void deleteTag_UnAuthorized () throws Exception{
+ mockMvc.perform(delete("/api/tags/{id}",ONE_ID))
+ .andExpect(status().isUnauthorized());
+ }
+
+
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/controller/UserControllerTest.java b/src/test/java/com/sopromadze/blogapi/controller/UserControllerTest.java
new file mode 100644
index 00000000..6fc0ebae
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/controller/UserControllerTest.java
@@ -0,0 +1,308 @@
+package com.sopromadze.blogapi.controller;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sopromadze.blogapi.model.Album;
+import com.sopromadze.blogapi.model.Post;
+import com.sopromadze.blogapi.model.role.RoleName;
+import com.sopromadze.blogapi.model.user.User;
+import com.sopromadze.blogapi.payload.PagedResponse;
+import com.sopromadze.blogapi.payload.UserIdentityAvailability;
+import com.sopromadze.blogapi.payload.UserProfile;
+import com.sopromadze.blogapi.payload.UserSummary;
+import com.sopromadze.blogapi.security.UserPrincipal;
+import com.sopromadze.blogapi.service.AlbumService;
+import com.sopromadze.blogapi.service.PostService;
+import com.sopromadze.blogapi.service.UserService;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.test.context.support.WithUserDetails;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+
+import java.util.Collections;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {SpringSecurityTestWebConfig.class})
+@AutoConfigureMockMvc
+class UserControllerTest {
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Autowired
+ private ObjectMapper objectMapper;
+
+ @MockBean
+ private UserService userService;
+
+ @MockBean
+ private PostService postService;
+
+ @MockBean
+ private AlbumService albumService;
+
+ @WithUserDetails("user")
+ @Test
+ void getCurrentUserSuccessTest() throws Exception{
+
+ //Instanciamos lo necesario
+
+ UserSummary userSummary = new UserSummary(
+ 1L,
+ "user",
+ "user",
+ "user"
+ );
+
+ ResponseEntity expected = new ResponseEntity< >(userSummary, HttpStatus.OK);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userService.getCurrentUser(any(UserPrincipal.class))).thenReturn(userSummary);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/users/me"))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ void getCurrentUserUnauthorizedTest() throws Exception{
+
+ //Instanciamos lo necesario
+
+ UserSummary userSummary = new UserSummary(
+ 1L,
+ "user",
+ "user",
+ "user"
+ );
+
+ ResponseEntity expected = new ResponseEntity< >(userSummary, HttpStatus.OK);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userService.getCurrentUser(any(UserPrincipal.class))).thenReturn(userSummary);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/users/me"))
+ .andExpect(status().isUnauthorized())
+ .andReturn();
+
+ }
+
+ @Test
+ void checkUsernameAvailabilitySuccessTest() throws Exception{
+
+ //Instanciamos lo necesario
+
+ UserIdentityAvailability userIdentityAvailability = new UserIdentityAvailability(true);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userService.checkUsernameAvailability("user")).thenReturn(userIdentityAvailability);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/users/checkUsernameAvailability")
+ .param("username", "user"))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ void checkUsernameAvailabilityBadRequestExceptionTest() throws Exception{
+
+ //Instanciamos lo necesario
+
+ UserIdentityAvailability userIdentityAvailability = new UserIdentityAvailability(true);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userService.checkUsernameAvailability("user")).thenReturn(userIdentityAvailability);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/users/checkUsernameAvailability")
+ .param("user", "user"))
+ .andExpect(status().isBadRequest())
+ .andReturn();
+
+ }
+
+ @Test
+ void checkEmailAvailabilitySuccessTest() throws Exception{
+
+ //Instanciamos lo necesario
+
+ UserIdentityAvailability userIdentityAvailability = new UserIdentityAvailability(true);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userService.checkEmailAvailability(any(String.class))).thenReturn(userIdentityAvailability);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/users/checkEmailAvailability")
+ .param("email", "luismimaquina@gmail.com"))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ void checkEmailAvailabilityBadRequestTest() throws Exception{
+
+ //Instanciamos lo necesario
+
+ UserIdentityAvailability userIdentityAvailability = new UserIdentityAvailability(true);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userService.checkEmailAvailability(any(String.class))).thenReturn(userIdentityAvailability);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/users/checkEmailAvailability")
+ .param("user", "luismimaquina@gmail.com"))
+ .andExpect(status().isBadRequest())
+ .andReturn();
+
+ }
+
+ @Test
+ void getUSerProfileSuccessTest() throws Exception{
+
+ //Instanciamos lo necesario
+
+ UserProfile userProfile = new UserProfile();
+
+ //Mockeamos lop necesario
+
+ Mockito.when(userService.getUserProfile(any(String.class))).thenReturn(userProfile);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/users//{username}/profile", "user"))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ void getPostsCreatedBySuccessTest() throws Exception{
+
+ //Instanciamos lo necesario
+
+ PagedResponse response = new PagedResponse<>();
+
+ MultiValueMap expected = new LinkedMultiValueMap<>();
+ expected.add("page", "0");
+ expected.add("size", "1");
+
+
+ //Mockeamos lo necesario
+
+ Mockito.when(postService.getPostsByCreatedBy(any(String.class), any(Integer.class), any(Integer.class)))
+ .thenReturn(response);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/users/{username}/posts", "user")
+ .params(expected))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ void getUserAlbumsSuccessTest() throws Exception{
+
+ //Instanciamos lo necesario
+
+ PagedResponse response = new PagedResponse<>();
+
+ //Mockeamos lo necesario
+
+ Mockito.when(albumService.getUserAlbums(any(String.class), any(Integer.class), any(Integer.class)))
+ .thenReturn(response);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/users/{username}/albums", "user"))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ @WithUserDetails("admin")
+ void addUserSuccessTest() throws Exception{
+
+ //Instanciamos lo necesario
+
+ User user = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+
+
+ ResponseEntity response = new ResponseEntity< >(user, HttpStatus.CREATED);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userService.addUser(any(User.class))).thenReturn(user);
+
+ //Implementamos el test
+
+ MvcResult mvcResult = mockMvc.perform(post("/api/users")
+ .content(objectMapper.writeValueAsString(user))
+ .contentType("application/json"))
+ .andExpect(status().isOk())
+ .andReturn();
+
+ }
+
+ @Test
+ void updateUser() {
+ }
+
+ @Test
+ void deleteUser() {
+ }
+
+ @Test
+ void giveAdmin() {
+ }
+
+ @Test
+ void takeAdmin() {
+ }
+
+ @Test
+ void setAddress() {
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/repository/AlbumRepositoryTest.java b/src/test/java/com/sopromadze/blogapi/repository/AlbumRepositoryTest.java
new file mode 100644
index 00000000..ccbce84d
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/repository/AlbumRepositoryTest.java
@@ -0,0 +1,71 @@
+package com.sopromadze.blogapi.repository;
+
+import com.sopromadze.blogapi.model.Album;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.time.Instant;
+import java.util.List;
+
+
+@ActiveProfiles("test")
+@DataJpaTest
+class AlbumRepositoryTest {
+
+ @Autowired
+ private TestEntityManager entityManager;
+
+ @Autowired
+ AlbumRepository albumRepository;
+
+ private static Album album;
+ private static Pageable pageable;
+ private static Long userId;
+
+ //Instanciamos lo necesario
+ @BeforeAll
+ static void beforeAll() {
+ album = new Album();
+ album.setTitle("Vacaciones 2020");
+ album.setCreatedAt(Instant.now());
+ album.setUpdatedAt(Instant.now());
+ userId = 1L;
+ album.setCreatedBy(userId);
+
+ pageable = PageRequest.of(0, 1);
+
+ }
+
+ @Test
+ void findByCreatedByTest() {
+
+ //Comprobación previa de el repositorio
+ List albums = albumRepository.findAll();
+ Assumptions.assumeTrue(albums.isEmpty());
+
+ //Guardado de prueba y preparación
+ entityManager.persist(album);
+
+ //Implementamos el test
+
+ Assertions.assertAll(
+ () -> Assertions.assertFalse(albumRepository.findAll().isEmpty()),
+ () -> Assertions.assertFalse(albumRepository.findByCreatedBy(userId, pageable).isEmpty()),
+ () -> Assertions.assertEquals("Vacaciones 2020", albumRepository.findByCreatedBy(userId, pageable).get().findFirst().get().getTitle())
+ );
+
+
+
+ }
+
+
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/repository/CommentRepositoryTest.java b/src/test/java/com/sopromadze/blogapi/repository/CommentRepositoryTest.java
new file mode 100644
index 00000000..2ca3e04f
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/repository/CommentRepositoryTest.java
@@ -0,0 +1,82 @@
+package com.sopromadze.blogapi.repository;
+
+import com.sopromadze.blogapi.model.Comment;
+import com.sopromadze.blogapi.model.Post;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.time.Instant;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+@DataJpaTest
+@ActiveProfiles("test")
+class CommentRepositoryTest {
+
+ @Autowired
+ private TestEntityManager entityManager;
+
+ @Autowired
+ private CommentRepository commentRepository;
+
+ private static Comment comment;
+ private static Post post;
+ private static Pageable pageable;
+
+ //Inicializamos lo necesario
+
+ @BeforeAll
+ static void beforeAll() {
+
+ comment = new Comment("Luismi eres un maquina apruebame porfa");
+ comment.setName("Alejandro");
+ comment.setEmail("bajo.diale20@triana.salesianos.edu");
+ comment.setCreatedAt(Instant.now());
+ comment.setUpdatedAt(Instant.now());
+
+ post = new Post();
+ post.setCreatedAt(Instant.now());
+ post.setUpdatedAt(Instant.now());
+ comment.setPost(post);
+
+ pageable = PageRequest.of(0, 1);
+
+
+ }
+
+ @Test
+ void findByPostIdTest() {
+
+ //Persistimos lo necesario y comprobaciones previas
+
+ List lista = commentRepository.findAll();
+ Assumptions.assumeTrue(lista.isEmpty());
+ entityManager.persist(post);
+ entityManager.persist(comment);
+ lista = commentRepository.findAll();
+ Assumptions.assumeFalse(lista.isEmpty());
+
+ Long postId = lista.stream().findFirst().get().getId();
+
+ Page comments = commentRepository.findByPostId(postId, pageable);
+
+ //Implementamos el test
+
+ Assertions.assertAll(
+ () -> Assertions.assertFalse(comments.isEmpty()),
+ () -> Assertions.assertEquals("Alejandro", comments.stream().findFirst().get().getName())
+ );
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/repository/PhotoRepositoryTest.java b/src/test/java/com/sopromadze/blogapi/repository/PhotoRepositoryTest.java
new file mode 100644
index 00000000..965054ad
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/repository/PhotoRepositoryTest.java
@@ -0,0 +1,67 @@
+package com.sopromadze.blogapi.repository;
+
+import com.sopromadze.blogapi.model.Album;
+import com.sopromadze.blogapi.model.Photo;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Sort;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+@DataJpaTest
+@ActiveProfiles("test")
+@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
+class PhotoRepositoryTest {
+
+ @Autowired
+ PhotoRepository photoRepository;
+
+ @Autowired
+ TestEntityManager testEntityManager;
+
+
+ private static List photos = new ArrayList<>();
+ private static Album al;
+
+ @BeforeEach
+ void setUp() {
+
+ Photo photo1 = new Photo();
+ photo1.setUrl("www.photo1.com");
+ photo1.setThumbnailUrl("www.photo1.com");
+ photo1.setTitle("Photo1");
+ photo1.setCreatedAt(Instant.now());
+ photo1.setUpdatedAt(Instant.now());
+
+ Photo photo2 = new Photo();
+ photo2.setUrl("www.photo2.com");
+ photo2.setThumbnailUrl("www.photo2.com");
+ photo2.setTitle("Photo2");
+ photo2.setCreatedAt(Instant.now());
+ photo2.setUpdatedAt(Instant.now());
+
+ photos.add(photo1);
+ photos.add(photo2);
+
+ al = new Album();
+ al.setPhoto(photos);
+ al.setTitle("Album Fotos");
+ al.setUpdatedAt(Instant.now());
+ al.setCreatedAt(Instant.now());
+ }
+ @Test
+ void findByAlbumId_Success() {
+ testEntityManager.persist(al);
+ assertNotNull(photoRepository.findByAlbumId(al.getId(), PageRequest.of(1, 1, Sort.Direction.DESC,"createdAt")));
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/repository/PostRepositoryTest.java b/src/test/java/com/sopromadze/blogapi/repository/PostRepositoryTest.java
new file mode 100644
index 00000000..f4328b3e
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/repository/PostRepositoryTest.java
@@ -0,0 +1,127 @@
+package com.sopromadze.blogapi.repository;
+
+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 org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.domain.Sort;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.*;
+
+@DataJpaTest
+@ActiveProfiles("test")
+@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
+@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
+class PostRepositoryTest {
+
+ @Autowired
+ PostRepository postRepository;
+
+ @Autowired
+ TestEntityManager testEntityManager;
+
+ @Test
+ void findByCreatedBy() {
+ User userP = new User("Manuel", "Fernández", "ManuFer", "manufer@gmail.com", "123456789");
+ userP.setCreatedAt(Instant.now());
+ userP.setUpdatedAt(Instant.now());
+ testEntityManager.persist(userP);
+
+ List postse = new ArrayList<>();
+
+ Post post1 = new Post();
+ post1.setTitle("titulo");
+ post1.setBody("body");
+ post1.setUser(userP);
+ post1.setCreatedBy(userP.getId());
+ post1.setCreatedAt(Instant.now());
+ post1.setUpdatedAt(Instant.now());
+ testEntityManager.persist(post1);
+
+ postse.add(post1);
+
+ Pageable pageable = PageRequest.of(0, 1, Sort.Direction.DESC, "createdAt");
+
+ Page posts = postRepository.findByCreatedBy(userP.getId(), pageable);
+ assertThat(posts).hasSize(1).contains(post1);
+ }
+
+ @Test
+ void findByCategory() {
+ Category cat = new Category();
+
+ Post post1 = new Post();
+ post1.setCategory(cat);
+ post1.setCreatedAt(Instant.now());
+ post1.setUpdatedAt(Instant.now());
+ testEntityManager.persist(post1);
+
+ //cat.setPosts(List.of(post1));
+ cat.setCreatedAt(Instant.now());
+ cat.setUpdatedAt(Instant.now());
+ testEntityManager.persist(cat);
+
+ Pageable pageable = PageRequest.of(0, 1, Sort.Direction.DESC, "createdAt");
+
+ Page posts = postRepository.findByCategoryId(cat.getId(), pageable);
+
+ assertThat(posts).contains(post1);
+
+ }
+
+ @Test
+ void findByTagsIn() {
+
+ Tag t = new Tag();
+ t.setCreatedAt(Instant.now());
+ t.setUpdatedAt(Instant.now());
+ testEntityManager.persist(t);
+
+ Post p = new Post();
+ p.setCreatedAt(Instant.now());
+ p.setUpdatedAt(Instant.now());
+ p.setTags(List.of(t));
+ testEntityManager.persist(p);
+
+ Pageable pageable = PageRequest.of(0, 1, Sort.Direction.DESC, "createdAt");
+
+ Iterable posts = postRepository.findByTagsIn(List.of(t), pageable);
+
+ assertThat(posts).hasSize(1).contains(p);
+
+ }
+
+ @Test
+ void countByCreatedBy() {
+
+ User userP = new User("Manuel", "Fernández", "ManuFer", "manufer@gmail.com", "123456789");
+ userP.setCreatedAt(Instant.now());
+ userP.setUpdatedAt(Instant.now());
+
+ Post p = new Post();
+ p.setCreatedAt(Instant.now());
+ p.setUpdatedAt(Instant.now());
+ p.setCreatedBy(userP.getId());
+ testEntityManager.persist(p);
+
+ Long cuenta = postRepository.countByCreatedBy(userP.getId());
+
+ assertEquals(1, cuenta);
+
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/repository/RoleRepositoryTest.java b/src/test/java/com/sopromadze/blogapi/repository/RoleRepositoryTest.java
new file mode 100644
index 00000000..b742af5b
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/repository/RoleRepositoryTest.java
@@ -0,0 +1,44 @@
+package com.sopromadze.blogapi.repository;
+
+import com.sopromadze.blogapi.model.role.Role;
+import com.sopromadze.blogapi.model.role.RoleName;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+@DataJpaTest
+@ActiveProfiles("test")
+@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
+class RoleRepositoryTest {
+
+ @Autowired
+ RoleRepository roleRepository;
+
+ @Autowired
+ TestEntityManager testEntityManager;
+
+ private static Role role;
+
+ @BeforeEach
+ void setUp() {
+
+ role = new Role();
+ role.setName(RoleName.ROLE_ADMIN);
+ }
+
+ @Test
+ void findByName_Success() {
+ testEntityManager.persist(role);
+ assertNotNull(roleRepository.findByName(role.getName()));
+ assertEquals(Optional.of(role),roleRepository.findByName(RoleName.ROLE_ADMIN));
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/repository/TagRepositoryTest.java b/src/test/java/com/sopromadze/blogapi/repository/TagRepositoryTest.java
new file mode 100644
index 00000000..de1e7106
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/repository/TagRepositoryTest.java
@@ -0,0 +1,63 @@
+package com.sopromadze.blogapi.repository;
+
+import com.sopromadze.blogapi.model.Album;
+import com.sopromadze.blogapi.model.Tag;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.time.Instant;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+@DataJpaTest
+@ActiveProfiles("test")
+class TagRepositoryTest {
+
+ @Autowired
+ private TestEntityManager entityManager;
+
+ @Autowired
+ TagRepository tagRepository;
+
+ private static Tag tag;
+ private static Pageable pageable;
+ private static Long tagId;
+
+ //Instanciamos lo necesario
+ @BeforeAll
+ static void beforeAll() {
+ tag = new Tag("Fiestas");
+ tag.setCreatedAt(Instant.now());
+ tag.setUpdatedAt(Instant.now());
+
+ }
+
+ @Test
+ void findByCreatedByTest() {
+
+ //Comprobación previa de el repositorio
+ List tags = tagRepository.findAll();
+ Assumptions.assumeTrue(tags.isEmpty());
+
+ //Guardado de prueba y preparación
+
+ entityManager.persist(tag);
+ tagId = tag.getId();
+
+ //Implementamos el test
+
+ Assertions.assertAll(
+ () -> Assertions.assertFalse(tagRepository.findAll().isEmpty()),
+ () -> Assertions.assertEquals(tagId, tagRepository.findByName("Fiestas").getId())
+ );
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/repository/TodoRepositoryTest.java b/src/test/java/com/sopromadze/blogapi/repository/TodoRepositoryTest.java
new file mode 100644
index 00000000..ad9d10c9
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/repository/TodoRepositoryTest.java
@@ -0,0 +1,44 @@
+package com.sopromadze.blogapi.repository;
+import org.junit.jupiter.api.BeforeEach;
+import com.sopromadze.blogapi.model.user.User;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Sort;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.time.Instant;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+@DataJpaTest
+@ActiveProfiles("test")
+@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
+class TodoRepositoryTest {
+
+ @Autowired
+ TodoRepository todoRepository;
+
+ @Autowired
+ TestEntityManager testEntityManager;
+
+ private static User user;
+
+ @BeforeEach
+ void setUp() {
+
+ user = new User("Pepe","Palomo","pepepalomo","pepepalomo@gmail.com","658");
+ user.setCreatedAt(Instant.now());
+ user.setCreatedAt(Instant.now());
+ user.setUpdatedAt(Instant.now());
+ }
+
+ @Test
+ void findByCreatedBy_Success() {
+ testEntityManager.persist(user);
+ assertNotNull(todoRepository.findByCreatedBy(user.getId(), PageRequest.of(1, 1, Sort.Direction.DESC,"createdAt")));
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/repository/UserRepositoryTest.java b/src/test/java/com/sopromadze/blogapi/repository/UserRepositoryTest.java
new file mode 100644
index 00000000..116efd73
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/repository/UserRepositoryTest.java
@@ -0,0 +1,113 @@
+package com.sopromadze.blogapi.repository;
+
+import com.sopromadze.blogapi.exception.ResourceNotFoundException;
+import com.sopromadze.blogapi.model.role.RoleName;
+import com.sopromadze.blogapi.model.user.User;
+import static org.junit.jupiter.api.Assertions.*;
+
+import com.sopromadze.blogapi.security.UserPrincipal;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.time.Instant;
+import java.util.Collections;
+
+@DataJpaTest
+@ActiveProfiles("test")
+@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
+@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
+class UserRepositoryTest {
+
+ @Autowired
+ UserRepository userRepository;
+
+ @Autowired
+ TestEntityManager testEntityManager;
+
+
+ @Test
+ void findByUserNameSuccess(){
+ User user= new User("Luismi","Lopez","Ligre","luismilopezmagaña@salesianos.edu","12345678");
+ user.setCreatedAt(Instant.now());
+ user.setUpdatedAt(Instant.now());
+ testEntityManager.persist(user);
+ assertNotNull(userRepository.findByUsername("Ligre").get());
+ }
+
+ @Test
+ void findByEmail_Success(){
+ User user= new User("Luismi","Lopez","Ligre","luismilopezmagaña@salesianos.edu","12345678");
+ user.setCreatedAt(Instant.now());
+ user.setUpdatedAt(Instant.now());
+ testEntityManager.persist(user);
+ assertNotNull(userRepository.findByEmail("luismilopezmagaña@salesianos.edu").get());
+ }
+
+ @Test
+ void existByUserName_Success(){
+ User user= new User("Luismi","Lopez","Ligre","luismilopezmagaña@salesianos.edu","12345678");
+ user.setCreatedAt(Instant.now());
+ user.setUpdatedAt(Instant.now());
+ testEntityManager.persist(user);
+ assertTrue(userRepository.existsByUsername("Ligre"));
+ }
+
+ @Test
+ void existByEmail_Success(){
+ User user= new User("Luismi","Lopez","Ligre","luismilopezmagaña@salesianos.edu","12345678");
+ user.setCreatedAt(Instant.now());
+ user.setUpdatedAt(Instant.now());
+ testEntityManager.persist(user);
+ assertTrue(userRepository.existsByEmail("luismilopezmagaña@salesianos.edu"));
+ }
+
+ @Test
+ void findByUsernameOrEmail_Success(){
+ User user= new User("Luismi","Lopez","Ligre","luismilopezmagaña@salesianos.edu","12345678");
+ user.setCreatedAt(Instant.now());
+ user.setUpdatedAt(Instant.now());
+ testEntityManager.persist(user);
+ assertNotNull(userRepository.findByUsernameOrEmail("Ligre","luismilopezmagaña@salesianos.edu"));
+ }
+
+ @Test
+ void getUserByName_Success(){
+ User user= new User("Luismi","Lopez","Ligre","luismilopezmagaña@salesianos.edu","12345678");
+ user.setCreatedAt(Instant.now());
+ user.setUpdatedAt(Instant.now());
+ testEntityManager.persist(user);
+ assertNotNull(userRepository.getUserByName("Ligre"));
+ }
+ @Test
+ void getUserByName_ResourceNotFoundException(){
+ User user= new User("Luismi","Lopez","Leopardo","luismilopezmagaña@salesianos.edu","12345678");
+ user.setCreatedAt(Instant.now());
+ user.setUpdatedAt(Instant.now());
+ testEntityManager.persist(user);
+ assertThrows(ResourceNotFoundException.class,()-> userRepository.getUserByName("Ligre"));
+ }
+
+ @Test
+ void getUserSuccess (){
+ UserPrincipal userPrincipal= new UserPrincipal(1L, "Luismi","Lopez", "Ligre","luismilopezmagaña@salesianos.edu","12345678", Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+ User user= new User("Luismi","Lopez","Ligre","luismilopezmagaña@salesianos.edu","12345678");
+ user.setCreatedAt(Instant.now());
+ user.setUpdatedAt(Instant.now());
+ testEntityManager.persist(user);
+ assertNotNull(userRepository.getUser(userPrincipal));
+ }
+
+
+
+
+
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/service/TagServiceTest.java b/src/test/java/com/sopromadze/blogapi/service/TagServiceTest.java
new file mode 100644
index 00000000..0f94059e
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/service/TagServiceTest.java
@@ -0,0 +1,166 @@
+package com.sopromadze.blogapi.service;
+
+import com.sopromadze.blogapi.exception.ResourceNotFoundException;
+import com.sopromadze.blogapi.exception.UnauthorizedException;
+import com.sopromadze.blogapi.model.Tag;
+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.PagedResponse;
+import com.sopromadze.blogapi.repository.TagRepository;
+import com.sopromadze.blogapi.security.UserPrincipal;
+import com.sopromadze.blogapi.service.impl.TagServiceImpl;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+import org.springframework.data.domain.*;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class TagServiceTest {
+
+ @Mock
+ private TagRepository tagRepository;
+
+ @InjectMocks
+ TagServiceImpl tagService;
+
+ static Tag t;
+
+ @BeforeEach
+ void init(){
+ t = new Tag("yoquese");
+ t.setCreatedBy(6L);
+ t.setId(4L);
+ }
+
+ @Test
+ void getTagById_success(){
+
+ when(tagRepository.findById(anyLong())).thenReturn(Optional.of(t));
+
+ assertEquals(t, tagService.getTag(4L));
+ }
+
+ @Test
+ void getTagById_failure(){
+
+ when(tagRepository.findById(anyLong())).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class, () -> tagService.getTag(4L));
+ }
+
+ @Test
+ void addTag_success(){
+
+ Role r = new Role(RoleName.ROLE_USER);
+
+ List roles = new ArrayList();
+ roles.add(r);
+
+ User user = new User("Manuel", "Fernández", "ManuFer", "manufer@gmail.com", "123456789");
+ user.setRoles(roles);
+
+ UserPrincipal userP = UserPrincipal.create(user);
+
+ when(tagRepository.save(t)).thenReturn(t);
+
+ assertEquals(t, tagService.addTag(t, userP));
+
+ }
+
+ @Test
+ void addTag_fail(){
+
+ Tag t = new Tag(null);
+
+ Role r = new Role(RoleName.ROLE_USER);
+
+ List roles = new ArrayList();
+ roles.add(r);
+
+ User user = new User("Manuel", "Fernández", "ManuFer", "manufer@gmail.com", "123456789");
+ user.setRoles(roles);
+
+ UserPrincipal userP = UserPrincipal.create(user);
+
+ when(tagRepository.save(t)).thenReturn(null);
+
+ assertEquals(null, tagService.addTag(t, userP));
+
+ }
+
+ @Test
+ void deleteTag_success(){
+
+ UserPrincipal userP = new UserPrincipal(1L,"Manuel", "Fernández", "ManuFer", "manufer@gmail.com", "123456789", Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())));
+
+ when(tagRepository.findById(anyLong())).thenReturn(Optional.of(t));
+
+ ApiResponse apiResponse = tagService.deleteTag(5L, userP);
+
+ verify(tagRepository).deleteById(5L);
+
+ assertTrue(apiResponse.getSuccess());
+ }
+
+ @Test
+ void deleteTag_failure(){
+
+ UserPrincipal userP = new UserPrincipal(1L,"Manuel", "Fernández", "ManuFer", "manufer@gmail.com", "123456789", Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+
+ when(tagRepository.findById(anyLong())).thenReturn(Optional.of(t));
+
+ assertThrows(UnauthorizedException.class, () -> tagService.deleteTag(4L, userP));
+ }
+
+ @Test
+ void updateTag_success(){
+
+ UserPrincipal userP = new UserPrincipal(1L,"Manuel", "Fernández", "ManuFer", "manufer@gmail.com", "123456789", Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())));
+
+ when(tagRepository.findById(anyLong())).thenReturn(Optional.of(t));
+
+ Tag nt;
+ nt = new Tag("hola");
+ nt.setCreatedBy(1L);
+ nt.setId(4L);
+
+ when(tagRepository.save(t)).thenReturn(t);
+
+ assertEquals(t, tagService.updateTag(4L, nt, userP));
+ }
+
+ @Test
+ void pagedAllTags_success(){
+
+ Pageable pageable = PageRequest.of(1, 1, Sort.Direction.DESC, "createdAt");
+
+ List tags = new ArrayList<>();
+ tags.add(t);
+
+ Page tagPage = new PageImpl(tags);
+
+ when(tagRepository.findAll(pageable)).thenReturn(tagPage);
+
+ assertEquals(1, tagService.getAllTags(1, 1).getSize());
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/AlbumServiceImplTest.java b/src/test/java/com/sopromadze/blogapi/service/impl/AlbumServiceImplTest.java
new file mode 100644
index 00000000..867117a6
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/service/impl/AlbumServiceImplTest.java
@@ -0,0 +1,182 @@
+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.role.Role;
+import com.sopromadze.blogapi.model.role.RoleName;
+import com.sopromadze.blogapi.model.user.User;
+import com.sopromadze.blogapi.payload.AlbumResponse;
+import com.sopromadze.blogapi.payload.ApiResponse;
+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 org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+import org.mockito.stubbing.Answer;
+import org.modelmapper.ModelMapper;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageImpl;
+import org.springframework.data.domain.Pageable;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class AlbumServiceImplTest {
+
+ @Mock
+ AlbumRepository albumRepository;
+
+ @Mock
+ UserRepository userRepository;
+
+ @Mock
+ ModelMapper modelMapper;
+
+ @InjectMocks
+ AlbumServiceImpl albumService;
+
+ static Long ALBUM_ID=1L;
+ static Long USER_ID=1L;
+ static Album album;
+ static Album album2;
+ static User user;
+ static User user2;
+ static AlbumRequest albumRequest;
+ static AlbumResponse albumResponse;
+ static UserPrincipal userPrincipalUser;
+ static UserPrincipal userPrincipalAdmin;
+ static Role adminRole;
+ static ApiResponse apiResponse;
+
+ @BeforeEach
+ void init(){
+ albumResponse=new AlbumResponse();
+ user=new User(); user.setId(USER_ID);
+ user2=new User(); user2.setId(2L);
+ adminRole=new Role(RoleName.ROLE_ADMIN);
+ album=new Album();
+ album2=new Album();
+ albumRequest=new AlbumRequest(); albumRequest.setTitle("Cantando bajo la lluvia");
+ userPrincipalUser= new UserPrincipal(USER_ID, "Maria","Lopez", "user","marialopez@gmail.com","user", Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+ userPrincipalAdmin= new UserPrincipal(USER_ID, "Jose","Ramirez", "admin","joselito@gmail.com","admin", Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())));
+ apiResponse=new ApiResponse(Boolean.TRUE, "You successfully deleted album");
+ }
+
+
+
+ @Test
+ void addAlbum_Success(){
+ album.setUser(user);
+ doNothing().when(modelMapper).map(albumRequest,album);
+ when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ when(albumRepository.save(any(Album.class))).thenReturn(album);
+ assertNotNull(albumService.addAlbum(albumRequest,userPrincipalUser).getUser());
+ }
+
+ @Test
+ void updateAlbum_Success(){
+ String title= "Cantando bajo la lluvia";
+ Album a2 =new Album(); a2.setUser(user); a2.setTitle(title);
+ album.setUser(user);
+
+ when(albumRepository.findById(anyLong())).thenReturn(Optional.of(album));
+ when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ when(albumRepository.save(a2)).thenReturn(a2);
+
+ doAnswer(new Answer() {
+ @Override
+ public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
+ Album a1=invocationOnMock.getArgument(1);
+ Album a2=invocationOnMock.getArgument(2);
+ a2.setTitle(a1.getTitle());
+ return null;
+ }
+ }).when(modelMapper).map(a2,album);
+
+ assertEquals(title, albumService.updateAlbum(ALBUM_ID,albumRequest,userPrincipalAdmin).getTitle());
+ }
+
+ @Test
+ void getAlbum_Success (){
+ when(albumRepository.findById(anyLong())).thenReturn(Optional.of(album));
+ assertNotNull(albumService.getAlbum(ALBUM_ID));
+ }
+
+ @Test
+ void getAlbum_ResourceNotFoundException(){
+ when(albumRepository.findById(anyLong())).thenReturn(Optional.empty());
+ assertThrows(ResourceNotFoundException.class,()-> albumService.getAlbum(ALBUM_ID));
+ }
+
+ @Test
+ void updateAlbum_ResourceNotFoundException(){
+ when(albumRepository.findById(anyLong())).thenReturn(Optional.empty());
+ when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ assertThrows(ResourceNotFoundException.class,()-> albumService.updateAlbum(ALBUM_ID,albumRequest,userPrincipalUser));
+ }
+ @Test
+ void updateAlbum_BlogapiException(){
+ user.setId(USER_ID);
+ album.setUser(user);
+ when(albumRepository.findById(anyLong())).thenReturn(Optional.of(album));
+ when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user2);
+ assertThrows(BlogapiException.class,()-> albumService.updateAlbum(ALBUM_ID,albumRequest,userPrincipalUser));
+ }
+
+ @Test
+ void deleteAlbum_Success(){
+ user.setId(USER_ID);
+ album.setUser(user);
+ when(albumRepository.findById(anyLong())).thenReturn(Optional.of(album));
+ when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ doNothing().when(albumRepository).deleteById(anyLong());
+ assertEquals(apiResponse,albumService.deleteAlbum(ALBUM_ID,userPrincipalUser));
+ }
+
+ @Test
+ void deleteAlbum_BlogapiException(){
+ user.setId(USER_ID);
+ album.setUser(user);
+ when(albumRepository.findById(anyLong())).thenReturn(Optional.of(album));
+ when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user2);
+ assertThrows(BlogapiException.class,()-> albumService.deleteAlbum(ALBUM_ID,userPrincipalUser));
+ }
+
+ @Test
+ void deleteAlbum_ResourceNotFoundException(){
+ when(albumRepository.findById(anyLong())).thenReturn(Optional.empty());
+ when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ assertThrows(ResourceNotFoundException.class,()-> albumService.deleteAlbum(ALBUM_ID,userPrincipalUser));
+ }
+
+ @Test
+ void getUserAlbums_Success (){
+ List listAlbums =new ArrayList<>(); listAlbums.add(album);
+ Page pageableAlbum=new PageImpl(listAlbums);
+
+ when(userRepository.getUserByName(anyString())).thenReturn(user);
+ when(albumRepository.findByCreatedBy(anyLong(),any(Pageable.class))).thenReturn(pageableAlbum);
+
+ assertEquals(1,albumService.getUserAlbums("Jacoco",1,1).getSize());
+ }
+
+}
\ No newline at end of file
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..9737f3f9
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/service/impl/CategoryServiceImplTests.java
@@ -0,0 +1,334 @@
+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.role.Role;
+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 org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+import org.springframework.data.domain.*;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+
+import java.time.Instant;
+import java.util.*;
+
+import static com.sopromadze.blogapi.model.role.RoleName.ROLE_ADMIN;
+import static com.sopromadze.blogapi.model.role.RoleName.ROLE_USER;
+
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+public class CategoryServiceImplTests {
+
+ @Mock
+ private CategoryRepository categoryRepository;
+
+ @InjectMocks
+ private CategoryServiceImpl categoryServiceImpl;
+
+
+ @Test
+ void getAllCategoriesSuccessTest() {
+
+ //Instanciamos lo necesario
+
+ Category category1 = new Category(
+ "paisaje"
+ );
+ category1.setCreatedAt(Instant.now());
+
+ Category category2 = new Category(
+ "Montañas"
+ );
+ category2.setCreatedAt(Instant.now());
+
+ Category category3 = new Category(
+ "Playas"
+ );
+ category3.setCreatedAt(Instant.now());
+
+ Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC, "createdAt");
+
+ List list = List.of(category1, category2, category3);
+ Page page = new PageImpl<>(list);
+
+ PagedResponse pagedResponse = new PagedResponse<>(list, 0, 3, 3L, 1, true);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(categoryRepository.findAll(pageable)).thenReturn(page);
+
+ //Implementamos el test
+
+ Assertions.assertEquals(pagedResponse, categoryServiceImpl.getAllCategories(0, 3));
+
+ }
+
+ @Test
+ void getCategorySuccessTest() {
+
+ //Instanciamos lo necesario.
+
+ Category category = new Category(
+ "paisaje"
+ );
+ category.setId(1L);
+ Optional c = Optional.of(category);
+
+ Mockito.when(categoryRepository.findById(1l)).thenReturn(c);
+
+ //Implementamos el test
+
+ Assertions.assertEquals(category, categoryServiceImpl.getCategory(1L));
+
+ }
+
+ @Test
+ void getCategoryExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ Optional category = Optional.empty();
+
+ Mockito.when(categoryRepository.findById(1L)).thenReturn(category);
+
+ //Implementamos el test
+
+ Assertions.assertThrows(ResourceNotFoundException.class, () -> categoryServiceImpl.getCategory(1L));
+
+ }
+
+ @Test
+ void addCategorySuccessTest() {
+
+ //Instanciamos lo necesario
+
+ Category category = new Category(
+ "paisaje"
+ );
+ category.setId(1L);
+
+ UserPrincipal currentUser = new UserPrincipal(
+ 1L,
+ "Ale",
+ "Bajo", "diale",
+ "luismimaquina@gmail.com",
+ "1234",
+ null
+ );
+
+ //Mockeamos lo necesario
+
+ Mockito.when(categoryServiceImpl.addCategory(category, currentUser)).thenReturn(category);
+
+ //Implementamos el test
+
+ Assertions.assertEquals(category, categoryServiceImpl.addCategory(category, currentUser));
+
+ }
+
+ @Test
+ void updateCategorySuccessTest() {
+
+ //Instanciamos lo necesario
+
+ Category category = new Category("Paisajes");
+ category.setId(1L);
+ category.setCreatedBy(1L);
+
+ Category newCategory = new Category("Montañas");
+ newCategory.setId(1L);
+
+ User user = new User(
+ "Ale",
+ "Bajo",
+ "diale",
+ "luismimaquina@gmail.com",
+ "12345678"
+ );
+ user.setId(1L);
+ Role role = new Role(ROLE_ADMIN);
+ List roles = List.of(role);
+ user.setRoles(roles);
+
+ UserPrincipal currentUser = UserPrincipal.create(user);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(categoryRepository.findById(1L)).thenReturn(Optional.of(category));
+ Mockito.when(categoryRepository.save(newCategory)).thenReturn(newCategory);
+
+ //Implantamos el test
+
+ Assertions.assertEquals(newCategory.getId(), categoryServiceImpl.updateCategory(1L, newCategory, currentUser).getId());
+
+ }
+
+ @Test
+ void updateCategoryResourceNotFoundExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ Category category = new Category("Paisajes");
+ category.setId(1L);
+
+ UserPrincipal currentUser = new UserPrincipal(
+ 1L,
+ "Ale",
+ "Bajo", "diale",
+ "luismimaquina@gmail.com",
+ "1234",
+ null
+ );
+
+ //Mockeamos lo necesario
+
+ Mockito.when(categoryRepository.findById(1L)).thenReturn(Optional.empty());
+
+ //Implantamos el test
+
+ Assertions.assertThrows(ResourceNotFoundException.class, () -> categoryServiceImpl.updateCategory(1L, category, currentUser));
+
+ }
+
+ @Test
+ void updateCategoryUnauthorizedExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ Category category = new Category("Paisajes");
+ category.setId(1L);
+ category.setCreatedBy(1L);
+
+ Category newCategory = new Category("Montañas");
+ newCategory.setId(1L);
+
+ User badUser = new User(
+ "Ale",
+ "Bajo",
+ "diale",
+ "luismimaquina@gmail.com",
+ "12345678"
+ );
+ badUser.setId(5L);
+ Role role1 = new Role(ROLE_USER);
+ List roles1 = List.of(role1);
+ badUser.setRoles(roles1);
+
+ UserPrincipal badUserPr = UserPrincipal.create(badUser);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(categoryRepository.findById(1L)).thenReturn(Optional.of(category));
+
+ //Implantamos el test
+
+ Assertions.assertThrows(UnauthorizedException.class, () -> categoryServiceImpl.updateCategory(1L, newCategory, badUserPr));
+
+ }
+
+ @Test
+ void deleteCategorySuccessTest() {
+
+ //Instanciamos lo necesario
+
+ Category category = new Category("Paisajes");
+ category.setId(1L);
+ category.setCreatedBy(1L);
+
+ User user = new User(
+ "Ale",
+ "Bajo",
+ "diale",
+ "luismimaquina@gmail.com",
+ "12345678"
+ );
+ user.setId(1L);
+ Role role = new Role(ROLE_ADMIN);
+ List roles = List.of(role);
+ user.setRoles(roles);
+
+ UserPrincipal currentUser = UserPrincipal.create(user);
+
+ ResponseEntity responseEntity = new ResponseEntity<>(new ApiResponse(Boolean.TRUE, "You successfully deleted category"), HttpStatus.OK);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(categoryRepository.findById(1L)).thenReturn(Optional.of(category));
+ Mockito.doNothing().when(categoryRepository).deleteById(1L);
+
+ //Implementamos el test
+
+ Assertions.assertEquals(responseEntity, categoryServiceImpl.deleteCategory(1L, currentUser));
+
+ }
+
+ @Test
+ void deleteCategoryResourceNotFoundExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal currentUser = new UserPrincipal(
+ 1L,
+ "Ale",
+ "Bajo", "diale",
+ "luismimaquina@gmail.com",
+ "1234",
+ null
+ );
+
+ //Mockeamos lo necesario
+
+ Mockito.when(categoryRepository.findById(1L)).thenReturn(Optional.empty());
+
+ //Implantamos el test
+
+ Assertions.assertThrows(ResourceNotFoundException.class, () -> categoryServiceImpl.deleteCategory(1L, currentUser));
+
+ }
+
+ @Test
+ void deleteCategoryUnauthorizedExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ Category category = new Category("Paisajes");
+ category.setId(1L);
+ category.setCreatedBy(1L);
+
+ User badUser = new User(
+ "Ale",
+ "Bajo",
+ "diale",
+ "luismimaquina@gmail.com",
+ "12345678"
+ );
+ badUser.setId(5L);
+ Role role1 = new Role(ROLE_USER);
+ List roles1 = List.of(role1);
+ badUser.setRoles(roles1);
+
+ UserPrincipal badUserPr = UserPrincipal.create(badUser);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(categoryRepository.findById(1L)).thenReturn(Optional.of(category));
+
+ //Implantamos el test
+
+ Assertions.assertThrows(UnauthorizedException.class, () -> categoryServiceImpl.deleteCategory(1L, badUserPr));
+
+ }
+}
diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/CommentServiceImplTest.java b/src/test/java/com/sopromadze/blogapi/service/impl/CommentServiceImplTest.java
new file mode 100644
index 00000000..40f68bae
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/service/impl/CommentServiceImplTest.java
@@ -0,0 +1,279 @@
+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.role.RoleName;
+import com.sopromadze.blogapi.model.user.User;
+import com.sopromadze.blogapi.payload.ApiResponse;
+import com.sopromadze.blogapi.payload.CommentRequest;
+import com.sopromadze.blogapi.payload.PagedResponse;
+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 org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+import org.springframework.data.domain.*;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+
+import java.util.Collections;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class CommentServiceImplTest {
+
+ private static final Long POST_ID = 1234L;
+ private static final Long COMMENT_ID = 456L;
+ private static final Long USER_ID = 352L;
+ private static final int PAGE = 1;
+ private static final int SIZE = 1;
+ private static final String BODY = "Hola que hace";
+
+ @Mock
+ private CommentRepository commentRepository;
+
+ @Mock
+ private PostRepository postRepository;
+
+ @Mock
+ private UserRepository userRepository;
+
+ @InjectMocks
+ private CommentServiceImpl commentService;
+
+ @Test
+ //Dato de entrada Long id Post, dato de salida PagedResponse con los comentarios
+ void getAllComments_Success() {
+ Pageable pageable = getPageable();
+ when(commentRepository.findByPostId(POST_ID,pageable)).thenReturn(getComments());
+
+ PagedResponse response = commentService.getAllComments(POST_ID, PAGE, SIZE);
+ assertEquals(1,response.getTotalElements());
+ /*List idP = (List) response.getContent().stream().map(p-> p.getPost().getId());
+ assertTrue(idP.contains(POST_ID));*/
+ }
+
+
+ private Page getComments() {
+ return new PageImpl(Collections.singletonList(getCommentEntity()));
+ }
+
+ private User getUser(){
+ User user = new User();
+ user.setUsername("Pepe");
+ user.setLastName("Palotes");
+ user.setId(USER_ID);
+
+ return user;
+ }
+
+ private Pageable getPageable() {
+ return PageRequest.of(PAGE,SIZE, Sort.Direction.DESC, "createdAt");
+ }
+
+ @Test
+ //Dato de entrada Commentario, dato de salida comentario guardado
+ void addComment_Success() {
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ when(userRepository.getUser(getUserPrincipal())).thenReturn(getUser());
+ Comment commentSave = getCommentEntity();
+ commentSave.setId(null);
+ when(commentRepository.save(commentSave)).thenReturn(getCommentEntity());
+
+ Comment comment = commentService.addComment(getCommentRequest(), POST_ID, getUserPrincipal());
+ assertEquals(COMMENT_ID, comment.getId());
+ }
+
+ @Test
+ //Dato de entrada Id de un post que no existe, dato de salida ResourceNotFoundException
+ void addtComment_NotFound(){
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class, ()-> commentService.addComment(getCommentRequest(), POST_ID, getUserPrincipal()));
+ }
+
+ @Test
+ //Dato de entrada id del post y el id del comentario, dato de salida el comentario
+ void getComment_Success() {
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.of(getCommentEntity()));
+
+ Comment comment = commentService.getComment(POST_ID, COMMENT_ID);
+ assertEquals(POST_ID, comment.getPost().getId());
+ }
+
+ @Test
+ //Dato de entrada id de un post que no existe, dato de salida ResourceNotFoundException
+ void getComment_NotFound(){
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class, ()-> commentService.getComment(POST_ID, COMMENT_ID));
+ }
+
+ @Test
+ //Dato de entrada id de post, id de un comentario que no existe, dato de salida ResourceNotFoundException
+ void getComment_NotFoundComment(){
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class, () -> commentService.getComment(POST_ID,COMMENT_ID));
+ }
+
+ @Test
+ //Dato de entrada id del post diferente a la id del post del comentario, dato de salida BlogapiException
+ void getComment_BlogApi(){
+ getCommentEntity().getPost().setId(777L);
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ getCommentEntity().getPost().setId(78L);
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.of(getCommentEntity()));
+
+ assertThrows(BlogapiException.class, ()-> commentService.getComment(POST_ID,COMMENT_ID));
+ }
+
+ @Test
+ void updateComment_Success() {
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.of(getCommentEntity()));
+ when(commentRepository.save(getCommentEntity())).thenReturn(getCommentEntity());
+
+ Comment comment = commentService.updateComment(POST_ID, COMMENT_ID, getCommentRequest(), getUserPrincipal());
+ assertEquals(COMMENT_ID, comment.getId());
+ }
+
+ @Test
+ //Dato de entrada id del usuario diferente a la id del usuario logeado, dato de salida BlogapiException
+ void updateComment_NotPermission(){
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.of(getCommentEntity()));
+ getCommentEntity().getUser().setId(98L);
+
+ assertThrows(BlogapiException.class, () -> commentService.updateComment(POST_ID, COMMENT_ID, getCommentRequest(), getUserRoleUser()),
+ "YOU_DON_T_HAVE_PERMISSION_TO + \"update\" + THIS_COMMENT");
+ }
+
+ @Test
+ //Dato de entrada id del post diferente a la id por parámetro, datos de salida BlogapiException
+ void updateComment_BadRequest(){
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.of(getCommentEntity()));
+ getPost().setId(4586L);
+
+ assertThrows(BlogapiException.class, ()-> commentService.updateComment(POST_ID, COMMENT_ID, getCommentRequest(), getUserRoleUser()),
+ "BAD_REQUEST, COMMENT_DOES_NOT_BELONG_TO_POST");
+ }
+
+ @Test()
+ //Dato de entrada id de un post que no existe, datos de salida ResourceNotFoundException
+ void updateComment_NotFound(){
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class, () -> commentService.updateComment(POST_ID, COMMENT_ID, getCommentRequest(), getUserPrincipal()),
+ "POST_STR, ID_STR, postId");
+ }
+
+ @Test()
+ //Dato de entrada id de un comentario que no existe, datos de salida ResourceNotFoundException
+ void updateComment_NotFoundComment(){
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class, () -> commentService.updateComment(POST_ID, COMMENT_ID, getCommentRequest(), getUserPrincipal()),
+ "COMMENT_STR, ID_STR, id");
+ }
+
+ private UserPrincipal getUserPrincipal() {
+ UserPrincipal userPrincipal = new UserPrincipal(USER_ID, "Pepe","Palote", "pepalote","pepalote@gmail.com","1234", Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())));
+ return userPrincipal;
+ }
+
+ private UserPrincipal getUserRoleUser(){
+ UserPrincipal userPrincipal = new UserPrincipal(1655L, "Pepe","Palote", "pepalote","pepalote@gmail.com","1234", Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));;
+ return userPrincipal;
+ }
+
+ private Comment getCommentEntity() {
+ Comment comment = new Comment();
+ comment.setName("pepalote");
+ comment.setEmail("pepalote@gmail.com");
+ comment.setUser(getUser());
+ comment.setPost(getPost());
+ comment.setId(COMMENT_ID);
+ comment.setBody(BODY);
+ return comment;
+ }
+
+ private CommentRequest getCommentRequest(){
+ CommentRequest commentRequest = new CommentRequest();
+ commentRequest.setBody(BODY);
+ return commentRequest;
+ }
+
+ private Post getPost() {
+ Post post = new Post();
+ post.setUser(getUser());
+ post.setId(POST_ID);
+ return post;
+ }
+
+ @Test
+ //Dato de entrada id comentario, dato de salida ApiResponse (True)
+ void deleteComment_Success() {
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.of(getCommentEntity()));
+
+ ApiResponse apiResponse = commentService.deleteComment(POST_ID, COMMENT_ID, getUserPrincipal());
+ verify(commentRepository).deleteById(COMMENT_ID);
+ assertTrue(apiResponse.getSuccess(), "You successfully deleted comment");
+ }
+
+ @Test()
+ //Dato de entrada id de post que no existe, dato de salida ResourceNotFoundException
+ void deleteComment_NotFound(){
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class, () -> commentService.deleteComment(POST_ID, COMMENT_ID, getUserPrincipal()),
+ "POST_STR, ID_STR, postId");
+ }
+
+ @Test
+ //Dato de entrada id de comentario que no existe, dato de salida ResourceNotFoundException
+ void deleteComment_NotFoundComment(){
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class, ()-> commentService.deleteComment(POST_ID, COMMENT_ID, getUserPrincipal()),
+ "COMMENT_STR, ID_STR, id");
+ }
+
+ @Test
+ //Dato de entrada usuario no autorizado, dato de salida BlogapiException
+ void deleteComment_NotPermission(){
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.of(getCommentEntity()));
+
+ getCommentEntity().getUser().setId(98L);
+ assertThrows(BlogapiException.class, () -> commentService.deleteComment(POST_ID, COMMENT_ID, getUserRoleUser()),
+ "YOU_DON_T_HAVE_PERMISSION_TO + \"delete\" + THIS_COMMENT");
+ }
+
+ @Test
+ //Dato de entrada id del post diferente a la id del post del comentario, datos de salida ApiResponse (False)
+ void deleteComment_False(){
+ when(postRepository.findById(POST_ID)).thenReturn(Optional.of(getPost()));
+ getPost().setId(65983L);
+
+ when(commentRepository.findById(COMMENT_ID)).thenReturn(Optional.of(getCommentEntity()));
+ ApiResponse apiResponse = commentService.deleteComment(POST_ID, COMMENT_ID, getUserPrincipal());
+ assertFalse(!apiResponse.getSuccess(),"COMMENT_DOES_NOT_BELONG_TO_POST");
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/PostServiceImplTest.java b/src/test/java/com/sopromadze/blogapi/service/impl/PostServiceImplTest.java
new file mode 100644
index 00000000..c60a9e73
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/service/impl/PostServiceImplTest.java
@@ -0,0 +1,239 @@
+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.role.RoleName;
+import com.sopromadze.blogapi.model.user.User;
+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 org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.data.domain.*;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+
+
+import java.util.List;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+@ExtendWith(MockitoExtension.class)
+class PostServiceImplTest {
+
+ @Mock
+ PostRepository postRepository;
+
+ @Mock
+ UserRepository userRepository;
+
+ @Mock
+ CategoryRepository categoryRepository;
+
+ @Mock
+ TagRepository tagRepository;
+
+ @InjectMocks
+ PostServiceImpl postService;
+
+ static Long ONE_ID=1L;
+ static int ONE =1;
+ static Pageable pageable;
+ static Page page;
+ static Post post;
+ static User user;
+ static Category category;
+ static Tag tag;
+ static UserPrincipal userPrincipalUser,userPrincipalAdmin;
+
+ @BeforeEach
+ void init(){
+ pageable = PageRequest.of(ONE, ONE, Sort.Direction.DESC,"a");
+ user= new User();user.setFirstName("Paco");user.setId(ONE_ID);
+ post=new Post();post.setUser(user);
+ page= new PageImpl(List.of(post),pageable, ONE);
+ tag=new Tag();tag.setName("Super tag");tag.setId(ONE_ID);tag.setPosts(List.of(post));
+ userPrincipalUser= new UserPrincipal(2L, "Maria","Lopez", "user","marialopez@gmail.com","user", List.of(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+ userPrincipalAdmin= new UserPrincipal(ONE_ID, "Jose","Ramirez", "admin","joselito@gmail.com","admin", List.of(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())));
+ category=new Category("Juego");category.setId(ONE_ID);
+ }
+
+ @Test
+ void getAllPosts_Success (){
+ lenient().when(postRepository.findAll(any(Pageable.class))).thenReturn(page);
+
+ assertNotNull(postService.getAllPosts(ONE, ONE));
+ assertEquals(List.of(post),postService.getAllPosts(ONE, ONE).getContent());
+ }
+
+ @Test
+ void getPostsByCreatedBy_Success (){
+
+ lenient().when(userRepository.getUserByName(anyString())).thenReturn(user);
+ lenient().when(postRepository.findByCreatedBy(anyLong(),any(Pageable.class))).thenReturn(page);
+
+ assertNotNull(postService.getPostsByCreatedBy("Paco", ONE, ONE));
+ assertEquals(1,postService.getPostsByCreatedBy("Paco" , ONE, ONE).getSize());
+ }
+
+ @Test
+ void getPostsByCategory_Success (){
+
+ lenient().when(categoryRepository.findById(anyLong())).thenReturn(Optional.of(category));
+ lenient().when(postRepository.findByCategoryId(anyLong(),any(Pageable.class))).thenReturn(page);
+
+ assertNotNull(postService.getPostsByCategory(ONE_ID, ONE, ONE));
+ assertEquals(1,postService.getPostsByCategory(ONE_ID, ONE, ONE).getContent().size());
+ }
+
+ @Test
+ void getPostsByCategory_ResourceNotFoundException(){
+
+ lenient().when(categoryRepository.findById(anyLong())).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class,()->postService.getPostsByCategory(ONE_ID, ONE, ONE));
+ }
+
+ @Test
+ void getPostsByTag_Success (){
+
+ lenient().when(tagRepository.findById(anyLong())).thenReturn(Optional.of(tag));
+ lenient().when(postRepository.findByTagsIn(anyList(),any(Pageable.class))).thenReturn(page);
+
+ assertNotNull(postService.getPostsByTag(ONE_ID, ONE, ONE));
+ assertEquals(1,postService.getPostsByTag(ONE_ID, ONE, ONE).getContent().size());
+ }
+
+ @Test
+ void getPostsByTag_ResourceNotFoundException(){
+
+ lenient().when(tagRepository.findById(anyLong())).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class,()->postService.getPostsByTag(ONE_ID, ONE, ONE));
+ }
+
+ @Test
+ void updatePost_Success(){
+
+ PostRequest dto=new PostRequest(); dto.setCategoryId(ONE_ID); dto.setTitle("Party");dto.setBody("En CasaBlanca");
+ lenient().when(postRepository.findById(anyLong())).thenReturn(Optional.of(post));
+ lenient().when(categoryRepository.findById(anyLong())).thenReturn(Optional.of(category));
+ lenient().when(postRepository.save(post)).thenReturn(post);
+
+ assertNotNull(postService.updatePost(ONE_ID,dto,userPrincipalAdmin));
+ assertEquals("Party",postService.updatePost(ONE_ID,dto,userPrincipalAdmin).getTitle());
+ }
+
+ @Test
+ void updatePost_ResourceNotFoundException_Post(){
+ PostRequest dto=new PostRequest(); dto.setCategoryId(ONE_ID); dto.setTitle("Party");dto.setBody("En CasaBlanca");
+ when(postRepository.findById(anyLong())).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class,()->postService.updatePost(ONE_ID,dto,userPrincipalAdmin));
+ }
+
+ @Test
+ void updatePost_ResourceNotFoundException_Category(){
+ PostRequest dto=new PostRequest(); dto.setCategoryId(ONE_ID); dto.setTitle("Party");dto.setBody("En CasaBlanca");
+ lenient().when(categoryRepository.findById(anyLong())).thenReturn(Optional.empty());
+ lenient().when(postRepository.findById(anyLong())).thenReturn(Optional.of(post));
+
+ assertThrows(ResourceNotFoundException.class,()->postService.updatePost(ONE_ID,dto,userPrincipalAdmin));
+ }
+
+ @Test
+ void updatePost_UnauthorizedException(){
+ PostRequest dto=new PostRequest(); dto.setCategoryId(ONE_ID); dto.setTitle("Party");dto.setBody("En CasaBlanca");
+
+ lenient().when(postRepository.findById(anyLong())).thenReturn(Optional.of(post));
+ lenient().when(categoryRepository.findById(anyLong())).thenReturn(Optional.of(category));
+
+
+ assertThrows(UnauthorizedException.class,()->postService.updatePost(ONE_ID,dto,userPrincipalUser));
+ }
+
+ @Test
+ void deletePost_Success(){
+ lenient().when(postRepository.findById(anyLong())).thenReturn(Optional.of(post));
+ doNothing().when(postRepository).deleteById(anyLong());
+
+ assertNotNull(postService.deletePost(ONE_ID,userPrincipalAdmin));
+ assertEquals("You successfully deleted post",postService.deletePost(ONE_ID,userPrincipalAdmin).getMessage());
+ }
+
+ @Test
+ void deletePost_ResourceNotFoundException(){
+ when(postRepository.findById(anyLong())).thenReturn(Optional.empty());
+ assertThrows(ResourceNotFoundException.class,()-> postService.deletePost(ONE_ID,userPrincipalAdmin));
+ }
+
+ @Test
+ void deletePost_UnauthorizedException(){
+ when(postRepository.findById(anyLong())).thenReturn(Optional.of(post));
+ assertThrows(UnauthorizedException.class,()-> postService.deletePost(ONE_ID,userPrincipalUser));
+ }
+
+ @Test
+ void addPost_Success (){
+ Tag tag2=new Tag(); tag2.setName("TagName");tag2.setId(ONE_ID);tag2.setPosts(List.of(new Post()));
+ User user2= new User();user2.setFirstName("Paco");user.setId(ONE_ID);
+ Category category2=new Category(); category2.setName("Zancos");category2.setId(ONE_ID);
+ Post post1= new Post();post1.setUser(user2);post1.setCategory(category2);post1.setTags(List.of(tag2));
+ PostRequest dto=new PostRequest(); dto.setCategoryId(ONE_ID); dto.setTitle("Party");dto.setBody("En CasaBlanca");
+
+ lenient().when(userRepository.findById(anyLong())).thenReturn(Optional.of(user2));
+ lenient().when(categoryRepository.findById(anyLong())).thenReturn(Optional.of(category2));
+ lenient().when(tagRepository.findByName(anyString())).thenReturn(tag2);
+ lenient().when(tagRepository.save(any(Tag.class))).thenReturn(tag2);
+ lenient().when(postRepository.save(any(Post.class))).thenReturn(post1);
+
+ assertNotNull(postService.addPost(dto,userPrincipalAdmin));
+ assertEquals("Zancos",postService.addPost(dto,userPrincipalAdmin).getCategory());
+ }
+
+ @Test
+ void addPost_ResourceNotFoundException_User (){
+ PostRequest dto=new PostRequest(); dto.setCategoryId(ONE_ID); dto.setTitle("Party");dto.setBody("En CasaBlanca");
+ when(userRepository.findById(anyLong())).thenReturn(Optional.empty());
+ assertThrows(ResourceNotFoundException.class,()->postService.addPost(dto,userPrincipalAdmin));
+ }
+
+ @Test
+ void addPost_ResourceNotFoundException_Category(){
+ User user2= new User();user2.setFirstName("Paco");user.setId(ONE_ID);
+ Category category2=new Category(); category2.setName("Zancos");category2.setId(ONE_ID);
+ PostRequest dto=new PostRequest(); dto.setCategoryId(ONE_ID); dto.setTitle("Party");dto.setBody("En CasaBlanca");
+
+ lenient().when(userRepository.findById(anyLong())).thenReturn(Optional.of(user2));
+ lenient().when(categoryRepository.findById(anyLong())).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class,()->postService.addPost(dto,userPrincipalAdmin));
+ }
+
+ @Test
+ void getPost_Success(){
+ when(postRepository.findById(anyLong())).thenReturn(Optional.of(post));
+ assertEquals(post,postService.getPost(ONE_ID));
+ }
+
+ @Test
+ void getPost_ResourceNotFoundException(){
+ when(postRepository.findById(anyLong())).thenReturn(Optional.empty());
+ assertThrows(ResourceNotFoundException.class,()->postService.getPost(ONE_ID));
+ }
+
+
+
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/TodoServiceImplTest.java b/src/test/java/com/sopromadze/blogapi/service/impl/TodoServiceImplTest.java
new file mode 100644
index 00000000..6f25998b
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/service/impl/TodoServiceImplTest.java
@@ -0,0 +1,751 @@
+package com.sopromadze.blogapi.service.impl;
+
+import com.sopromadze.blogapi.exception.BadRequestException;
+import com.sopromadze.blogapi.exception.ResourceNotFoundException;
+import com.sopromadze.blogapi.exception.UnauthorizedException;
+import com.sopromadze.blogapi.model.Todo;
+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.PagedResponse;
+import com.sopromadze.blogapi.repository.TodoRepository;
+import com.sopromadze.blogapi.repository.UserRepository;
+import com.sopromadze.blogapi.security.UserPrincipal;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageImpl;
+import org.springframework.data.domain.Pageable;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class TodoServiceImplTest {
+
+ @Mock
+ private TodoRepository todoRepository;
+
+ @Mock
+ private UserRepository userRepository;
+
+ @InjectMocks
+ private TodoServiceImpl todoService;
+
+ @Test
+ void completeTodoSuccessTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user.setId(1L);
+
+ Todo todo = new Todo();
+ todo.setUser(user);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.of(todo));
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ Mockito.when(todoRepository.save(any(Todo.class))).thenReturn(todo);
+
+ //Implementamos el test
+
+ Assertions.assertEquals(todo, todoService.completeTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void completeTodoResourceNotFoundExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ //Mockeamos lo necesario
+
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.empty());
+
+ //Implementamos el test
+
+ Assertions.assertThrows(ResourceNotFoundException.class, () -> todoService.completeTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void completeTodoUnauthorizedExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user1 = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user1.setId(1L);
+
+ User user2 = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user2.setId(2L);
+
+ Todo todo = new Todo();
+ todo.setUser(user2);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.of(todo));
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user1);
+
+ //Implementamos el test
+
+ Assertions.assertThrows(UnauthorizedException.class, () -> todoService.completeTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void unCompleteTodoSuccessTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user.setId(1L);
+
+ Todo todo = new Todo();
+ todo.setUser(user);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.of(todo));
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ Mockito.when(todoRepository.save(any(Todo.class))).thenReturn(todo);
+
+ //Implementamos el test
+
+ Assertions.assertEquals(todo, todoService.unCompleteTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void unCompleteTodoResourceNotFoundExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ //Mockeamos lo necesario
+
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.empty());
+
+ //Implementamos el test
+
+ Assertions.assertThrows(ResourceNotFoundException.class, () -> todoService.unCompleteTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void unCompleteTodoUnauthorizedExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user1 = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user1.setId(1L);
+
+ User user2 = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user2.setId(2L);
+
+ Todo todo = new Todo();
+ todo.setUser(user2);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.of(todo));
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user1);
+
+ //Implementamos el test
+
+ Assertions.assertThrows(UnauthorizedException.class, () -> todoService.unCompleteTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void getAllTodosSuccessTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ Todo todo1 = new Todo();
+ Todo todo2 = new Todo();
+ Todo todo3 = new Todo();
+ List lista = List.of(todo1, todo2, todo3);
+
+ Page todos = new PageImpl(lista);
+
+ PagedResponse result= new PagedResponse<>(lista, todos.getNumber(), todos.getSize(), todos.getTotalElements(),
+ todos.getTotalPages(), todos.isLast());
+
+ //Mockeamos lo necesario
+
+ Mockito.when(todoRepository.findByCreatedBy(any(Long.class), any(Pageable.class))).thenReturn(todos);
+
+ //Implementamos el test
+
+ Assertions.assertEquals(result, todoService.getAllTodos(userPrincipal, 0, 1));
+
+ }
+
+ @Test
+ void getAllTodosBadRequestExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ //Implementamos los test
+
+ Assertions.assertAll(
+ () -> Assertions.assertThrows(BadRequestException.class, () -> todoService.getAllTodos(userPrincipal, -1, 1)),
+ () -> Assertions.assertThrows(BadRequestException.class, () -> todoService.getAllTodos(userPrincipal, 0, -1)),
+ () -> Assertions.assertThrows(BadRequestException.class, () -> todoService.getAllTodos(userPrincipal, 1, 35))
+ );
+
+ }
+
+
+
+ @Test
+ void addTodo() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user.setId(1L);
+
+ Todo todo = new Todo();
+ todo.setUser(user);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ Mockito.when(todoRepository.save(any(Todo.class))).thenReturn(todo);
+
+ //Implementamos el test
+
+ Assertions.assertEquals(todo, todoService.addTodo(todo, userPrincipal));
+
+ }
+
+ @Test
+ void getTodoSuccessTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user.setId(1L);
+
+ Todo todo = new Todo();
+ todo.setUser(user);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.of(todo));
+
+ //Implementamos el test
+
+ Assertions.assertEquals(todo, todoService.getTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void getTodoResourceNotFoundExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user.setId(1L);
+
+ Todo todo = new Todo();
+ todo.setUser(user);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.empty());
+
+ //Implementamos el test
+
+ Assertions.assertThrows(ResourceNotFoundException.class, () -> todoService.getTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void getTodoUnauthorizedExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user1 = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user1.setId(1L);
+
+ User user2 = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user2.setId(2L);
+
+ Todo todo = new Todo();
+ todo.setUser(user2);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user1);
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.of(todo));
+
+ //Implementamos el test
+
+ Assertions.assertThrows(UnauthorizedException.class, () -> todoService.getTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void updateTodoSuccessTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user.setId(1L);
+
+ Todo todo = new Todo();
+ todo.setUser(user);
+
+ Todo newTodo = new Todo();
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.of(todo));
+ Mockito.when(todoRepository.save(any(Todo.class))).thenReturn(todo);
+
+ //Implementamos el test
+
+ Assertions.assertEquals(todo, todoService.updateTodo(1L, newTodo, userPrincipal));
+
+ }
+
+ @Test
+ void updateTodoResourceNotFoundExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user.setId(1L);
+
+ Todo todo = new Todo();
+ todo.setUser(user);
+
+ Todo newTodo = new Todo();
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.empty());
+
+ //Implementamos el test
+
+ Assertions.assertThrows(ResourceNotFoundException.class, () -> todoService.updateTodo(1L, newTodo, userPrincipal));
+
+ }
+
+ @Test
+ void updateTodoUnauthorizedExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user1 = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user1.setId(1L);
+
+ User user2 = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user2.setId(2L);
+
+ Todo todo = new Todo();
+ todo.setUser(user2);
+
+ Todo newTodo = new Todo();
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user1);
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.of(todo));
+
+ //Implementamos el test
+
+ Assertions.assertThrows(UnauthorizedException.class, () -> todoService.updateTodo(1L, newTodo, userPrincipal));
+
+ }
+
+ @Test
+ void deleteTodoSuccessTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user.setId(1L);
+
+ Todo todo = new Todo();
+ todo.setUser(user);
+
+ ApiResponse response = new ApiResponse(Boolean.TRUE, "You successfully deleted todo");
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.of(todo));
+ Mockito.doNothing().when(todoRepository).deleteById(any(Long.class));
+
+ //Implementamos el test
+
+ Assertions.assertEquals(response, todoService.deleteTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void deleteTodoResourceNotFoundExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user.setId(1L);
+
+ Todo todo = new Todo();
+ todo.setUser(user);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user);
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.empty());
+
+ //Implementamos el test
+
+ Assertions.assertThrows(ResourceNotFoundException.class, () -> todoService.deleteTodo(1L, userPrincipal));
+
+ }
+
+ @Test
+ void deleteTodoUnauthorizedExceptionTest() {
+
+ //Instanciamos lo necesario
+
+ UserPrincipal userPrincipal = new UserPrincipal(
+ 1L,
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString()))
+ );
+
+ User user1 = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user1.setId(1L);
+
+ User user2 = new User(
+ "user",
+ "user",
+ "user",
+ "user@gmail.com",
+ "user"
+ );
+ user2.setId(2L);
+
+ Todo todo = new Todo();
+ todo.setUser(user2);
+
+ //Mockeamos lo necesario
+
+ Mockito.when(userRepository.getUser(any(UserPrincipal.class))).thenReturn(user1);
+ Mockito.when(todoRepository.findById(any(Long.class))).thenReturn(Optional.empty());
+
+ //Implementamos el test
+
+ Assertions.assertThrows(ResourceNotFoundException.class, () -> todoService.deleteTodo(1L, userPrincipal));
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/sopromadze/blogapi/service/impl/UserServiceImplTest.java b/src/test/java/com/sopromadze/blogapi/service/impl/UserServiceImplTest.java
new file mode 100644
index 00000000..61664ef3
--- /dev/null
+++ b/src/test/java/com/sopromadze/blogapi/service/impl/UserServiceImplTest.java
@@ -0,0 +1,307 @@
+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.Address;
+import com.sopromadze.blogapi.model.user.User;
+import com.sopromadze.blogapi.payload.*;
+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.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.crypto.password.PasswordEncoder;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class UserServiceImplTest {
+
+ @Mock
+ private UserRepository userRepository;
+ @Mock
+ private PostRepository postRepository;
+ @Mock
+ private RoleRepository roleRepository;
+ @Mock
+ private PasswordEncoder passwordEncoder;
+
+ @InjectMocks
+ UserServiceImpl userService;
+
+ private static UserPrincipal userPrincipal;
+ private static UserPrincipal userPrincipalUser;
+ private static User user;
+ private static Role role;
+ private static Role role2;
+ private static InfoRequest infoRequest;
+
+ @BeforeEach
+ void setUp() {
+ userPrincipal = new UserPrincipal(12L, "Pepe", "Palomo",
+ "pepepalomo", "pepepalomo@gmail.com", "1234",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_ADMIN.toString())));
+
+ userPrincipalUser = new UserPrincipal(56L, "Paola", "Carmona",
+ "paocarm", "paocarm@gmail.com", "1234",
+ Collections.singleton(new SimpleGrantedAuthority(RoleName.ROLE_USER.toString())));
+
+ Address address = new Address();
+ address.setId(2L);
+ address.setCity("Sevilla");
+ address.setStreet("Calle x");
+
+ user = new User();
+ user.setUsername("pepepalomo");
+ user.setId(12L);
+ user.setCreatedAt(Instant.now());
+ user.setFirstName("Pepe");
+ user.setLastName("Palomo");
+ user.setAddress(address);
+ user.setPhone("654548798");
+ user.setWebsite("www.palomo.com");
+
+ role = new Role();
+ role.setName(RoleName.ROLE_USER);
+
+ role2 = new Role();
+ role2.setName(RoleName.ROLE_ADMIN);
+
+ infoRequest = new InfoRequest();
+ infoRequest.setCity("Sevilla");
+ infoRequest.setCompanyName("Empresa");
+ infoRequest.setZipcode("554");
+ }
+
+ @Test
+ //Dato de entrada Id usuario, dato de salida Usuario Logeado
+ void getCurrentUser_Success() {
+ UserSummary userSummary = userService.getCurrentUser(userPrincipal);
+ assertEquals(userPrincipal.getId(), userSummary.getId(), "Este método te devuelve el usuario logeado");
+ }
+
+ @Test
+ //Dato de entrada Nombre de Usuario sin registrar, dato de salida un true ya que no se encuentra el nombre registrado
+ void checkUsernameAvailability_Success() {
+ when(userRepository.existsByUsername(userPrincipal.getUsername())).thenReturn(false);
+
+ UserIdentityAvailability userIdentityAvailability = userService.checkUsernameAvailability(userPrincipal.getUsername());
+ assertTrue(userIdentityAvailability.getAvailable().booleanValue(),
+ "Este método comprueba si el nombre de usuario es válido");
+ }
+
+ @Test
+ //Dato de entrada un Email, dato de salida un true porque no se encuentra registrado
+ void checkEmailAvailability_Success() {
+ when(userRepository.existsByEmail(userPrincipal.getEmail())).thenReturn(false);
+
+ UserIdentityAvailability userIdentityAvailability = userService.checkUsernameAvailability(userPrincipal.getEmail());
+ assertTrue(userIdentityAvailability.getAvailable().booleanValue(),
+ "Este método comprueba si el email de usuario es válido");
+ }
+
+ @Test
+ //Dato de entrada el Id, dato de salida el perfil de usuario del Id
+ void getUserProfile_Success() {
+ when(userRepository.getUserByName(user.getUsername())).thenReturn(user);
+ when(postRepository.countByCreatedBy(user.getId())).thenReturn(user.getId());
+
+ UserProfile userProfile = userService.getUserProfile(user.getUsername());
+ assertEquals(user.getId(), userProfile.getId());
+ }
+
+ @Test
+ //Dato de entrada un usuario, dato de salida el usuario registrado
+ void addUser_Success() {
+ when(userRepository.existsByUsername(user.getUsername())).thenReturn(false);
+ when(userRepository.existsByEmail(user.getEmail())).thenReturn(false);
+ when(roleRepository.findByName(RoleName.ROLE_USER)).thenReturn(Optional.of(role));
+ when(userRepository.save(user)).thenReturn(user);
+
+ User u = userService.addUser(user);
+ assertEquals(user.getId(),u.getId());
+ }
+
+ @Test
+ //Dato de entrada un nombre registrado, dato de salida BadRequest
+ void addUser_BadRequest(){
+ when(userRepository.existsByUsername(user.getUsername())).thenReturn(true);
+
+ assertThrows(BadRequestException.class, ()-> userService.addUser(user),
+ "Username is already taken");
+ }
+
+ @Test
+ //Dato de entrada email ya registrado, dato de salida BadRequest
+ void addUser_BadRequestEmail(){
+ when(userRepository.existsByUsername(user.getUsername())).thenReturn(false);
+ when(userRepository.existsByEmail(user.getEmail())).thenReturn(true);
+
+ assertThrows(BadRequestException.class, ()-> userService.addUser(user),
+ "Email is already taken");
+ }
+
+ @Test
+ //Dato de entrada usuario sin rol, dato de salida AppException
+ void addUser_AppException(){
+ when(userRepository.existsByUsername(user.getUsername())).thenReturn(false);
+ when(userRepository.existsByEmail(user.getEmail())).thenReturn(false);
+ when(roleRepository.findByName(RoleName.ROLE_USER)).thenReturn(Optional.empty());
+
+ assertThrows(AppException.class, ()-> userService.addUser(user),
+ "User role not set");
+ }
+
+ @Test
+ //Dato de entrada usuario, dato de salida usuario actualizado
+ void updateUser_Success() {
+ when(userRepository.getUserByName(user.getUsername())).thenReturn(user);
+ when(userRepository.save(user)).thenReturn(user);
+
+ User usuarioUpdate = userService.updateUser(user, user.getUsername(), userPrincipal);
+ assertEquals(userPrincipal.getId(), usuarioUpdate.getId());
+ }
+
+ @Test
+ //Dato de entrada usuario sin role de admin, dato de salida UnauthorizedException
+ void updateUser_Unauthorized(){
+ when(userRepository.getUserByName(user.getUsername())).thenReturn(user);
+
+ assertThrows(UnauthorizedException.class, ()-> userService.updateUser(user, user.getUsername(), userPrincipalUser),
+ "\"You don't have permission to update profile of: \" + username");
+ }
+
+ @Test
+ //Dato de entrada usuario, dato de salida ApiResponse (True)
+ void deleteUser_Success() {
+ when(userRepository.findByUsername(user.getUsername())).thenReturn(Optional.of(user));
+
+ ApiResponse apiResponse = userService.deleteUser(user.getUsername(), userPrincipal);
+ verify(userRepository).deleteById(user.getId());
+ assertTrue(apiResponse.getSuccess());
+ }
+
+ @Test
+ //Dato de entrada nulo, dato de salida ResourceNotFoundException
+ void deleteUser_NotFound(){
+ when(userRepository.findByUsername(user.getUsername())).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class, ()-> userService.deleteUser(user.getUsername(), userPrincipal),
+ "\"User\", \"id\", username");
+ }
+
+ @Test
+ //Dato de entrada user sin role de ADMIN, dato de salida AccessDeniedException
+ void deleteUser_AccesDenied(){
+ when(userRepository.findByUsername(user.getUsername())).thenReturn(Optional.of(user));
+ user.setId(548L);
+
+ assertThrows(AccessDeniedException.class, ()-> userService.deleteUser(user.getUsername(), userPrincipal),
+ "\"You don't have permission to delete profile of: \" + username");
+ }
+
+ @Test
+ //Dato de entrada usuario, dato de salida usuario con role de ADMIN
+ void giveAdmin_Success() {
+ when(userRepository.getUserByName(user.getUsername())).thenReturn(user);
+ when(roleRepository.findByName(role.getName())).thenReturn(Optional.of(role));
+ when(roleRepository.findByName(role2.getName())).thenReturn(Optional.of(role2));
+ when(userRepository.save(user)).thenReturn(user);
+
+ ApiResponse apiResponse = userService.giveAdmin(user.getUsername());
+ assertTrue(apiResponse.getSuccess());
+ //assertTrue(user.getRoles().contains(RoleName.ROLE_ADMIN));
+ }
+
+ @Test
+ //Dato de entrada Usuario sin role de Admin, dato de salida AppException
+ void giveAdmin_AppException(){
+ when(userRepository.getUserByName(user.getUsername())).thenReturn(user);
+ when(roleRepository.findByName(role.getName())).thenReturn(Optional.empty());
+
+ assertThrows(AppException.class, () -> userService.giveAdmin(user.getUsername()),
+ "User role not set");
+ }
+
+ @Test
+ //Dato de entrada Usuario con role de Admin pero sin role de usuario, dato de salida AppException
+ void giveAdmin_AppExceptionRole(){
+ when(userRepository.getUserByName(user.getUsername())).thenReturn(user);
+ when(roleRepository.findByName(role.getName())).thenReturn(Optional.of(role2));
+ when(roleRepository.findByName(role.getName())).thenReturn(Optional.empty());
+
+ assertThrows(AppException.class, () -> userService.giveAdmin(user.getUsername()),
+ "\"You gave ADMIN role to user: \" + username");
+ }
+
+ @Test
+ //Dato de entrada usuario con role de admin, dato de salida usuario sin role de admin
+ void removeAdmin_Success() {
+ user.setRoles(List.of(role2));
+ when(userRepository.getUserByName(user.getUsername())).thenReturn(user);
+ when(roleRepository.findByName(role.getName())).thenReturn(Optional.of(role));
+ when(userRepository.save(user)).thenReturn(user);
+
+ ApiResponse apiResponse = userService.removeAdmin(user.getUsername());
+ assertTrue(apiResponse.getSuccess());
+ assertFalse(user.getRoles().contains(RoleName.ROLE_ADMIN));
+ }
+
+ @Test
+ //Dato de entrada usuario sin role, dato de salida AppException
+ void removeAdmin_AppException(){
+ when(userRepository.getUserByName(user.getUsername())).thenReturn(user);
+ when(roleRepository.findByName(role.getName())).thenReturn(Optional.empty());
+
+ assertThrows(AppException.class, ()-> userService.removeAdmin(user.getUsername()),
+ "\"You took ADMIN role from user: \" + username");
+ }
+
+ @Test
+ //Dato de entrada datos de usuario, datos de salida datos de usuario actualizados
+ void setOrUpdateInfo_Success() {
+ when(userRepository.findByUsername(userPrincipal.getUsername())).thenReturn(Optional.of(user));
+ when(userRepository.save(user)).thenReturn(user);
+ when(postRepository.countByCreatedBy(user.getId())).thenReturn(1L);
+
+ UserProfile userProfile = userService.setOrUpdateInfo(userPrincipal, infoRequest);
+ assertEquals(user.getId(), userProfile.getId());
+ }
+
+ @Test
+ //Dato de entrada usuario no existente, dato de salida ResourceNotFoundException
+ void setOrUpdateInfo_NotFound(){
+ when(userRepository.findByUsername(userPrincipal.getUsername())).thenReturn(Optional.empty());
+
+ assertThrows(ResourceNotFoundException.class, ()-> userService.setOrUpdateInfo(userPrincipal, infoRequest),
+ "\"User\", \"username\", currentUser.getUsername()");
+ }
+
+ @Test
+ //Dato de entrada usuario sin role de admin, dato de salida AccessDeniedException
+ void setOrUpdateInfo_AccessDenied(){
+ when(userRepository.findByUsername(userPrincipalUser.getUsername())).thenReturn(Optional.of(user));
+
+ assertThrows(AccessDeniedException.class, ()-> userService.setOrUpdateInfo(userPrincipalUser, infoRequest),
+ "You don't have permission to update users profile");
+ }
+}
\ No newline at end of file