Skip to content

Commit

Permalink
29/12: write test for CategoryService
Browse files Browse the repository at this point in the history
  • Loading branch information
thuan committed Dec 29, 2023
1 parent e35c6ac commit 6558085
Show file tree
Hide file tree
Showing 5 changed files with 221 additions and 22 deletions.
3 changes: 3 additions & 0 deletions src/main/java/com/spotify/app/dto/CategoryDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,7 @@ public record CategoryDTO(Integer id,
String thumbnailPath,
Set<PlaylistResponse> playlists
) {
public CategoryDTO(Integer id) {
this(id, null, false, null, null, null);
}
}
9 changes: 9 additions & 0 deletions src/main/java/com/spotify/app/model/Category.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,13 @@ public String getCategoryParentTitle() {
}
return null;
}

public Category(Integer id) {
this.id = id;
}

public Category(String title) {
this.title = title;
}
}

48 changes: 29 additions & 19 deletions src/main/java/com/spotify/app/service/CategoryService.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class CategoryService {

public Set<CategoryDTO> listParent() {
Set<Category> categories = categoryRepository.listAllParent();
return CategoryMapper.INSTANCE.categoriesToCategoriesDTO(categories);
return categoryMapper.categoriesToCategoriesDTO(categories);
}

public Set<CategoryDTO> listByParentId(Integer parentId) {
Expand All @@ -52,7 +52,7 @@ public Category get(Integer cateId) {
return categoryRepository.
findById(cateId).
orElseThrow(() ->
new ResourceNotFoundException(String.format("category with id not found", cateId)));
new ResourceNotFoundException(String.format("category with id %d not found", cateId)));
}

public Set<CategoryDTO> findCategoryNameHome() {
Expand All @@ -75,42 +75,52 @@ private void checkCategoryExitByTitleWhenUpdate(Category underCheck,String titl
}

private void checkCategoryExitByTitle(String title) {
boolean check = categoryRepository.findByTitle(title).isPresent();
if(check) {
throw new DuplicateResourceException(String.format("category with title : [%s] existed" , title));
}

}

@Transactional
public void updateCategory(
Integer categoryId,
String title,
String categoryParentTitle
public void updateCategory( Integer categoryId, String title, String categoryParentTitle
) {
Category underUpdate = get(categoryId);
Category underUpdate = categoryRepository.
findById(categoryId).
orElseThrow(() ->
new ResourceNotFoundException(String.format("category with id %d not found", categoryId)));

checkCategoryExitByTitleWhenUpdate(underUpdate, title);
boolean check = categoryRepository.findByTitle(title).isPresent();
if (check && !underUpdate.getTitle().equals(title)) {
throw new DuplicateResourceException(String.format("category with title : [%s] existed" , title));
}
underUpdate.setTitle(title);

if(categoryParentTitle != null) {
Category parent = getByTitle(categoryParentTitle);
Category parent = categoryRepository.
findByTitle(title).
orElseThrow(() ->
new ResourceNotFoundException(
String.format("category with title: %s not found", title)
));
underUpdate.setCategoryParent(parent);
}
categoryRepository.save(underUpdate);
}


@Transactional
public void addCategory(
String title,
String categoryParentTitle
) {
public void addCategory(String title, String categoryParentTitle) {
Category underSave = new Category();
checkCategoryExitByTitle(title);
boolean check = categoryRepository.findByTitle(title).isPresent();
if(check) {
throw new DuplicateResourceException(String.format("category with title : [%s] existed" , title));
}
underSave.setTitle(title);

if(categoryParentTitle != null) {
Category parent = getByTitle(categoryParentTitle);
Category parent = categoryRepository.
findByTitle(title).
orElseThrow(() ->
new ResourceNotFoundException(
String.format("category with title: %s not found", title)
));
underSave.setCategoryParent(parent);
} else {
underSave.setCategoryParent(null);
Expand Down
3 changes: 0 additions & 3 deletions src/test/java/com/spotify/app/album/AlbumServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,13 @@
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
Expand Down
180 changes: 180 additions & 0 deletions src/test/java/com/spotify/app/category/CategoryServiceTest.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,184 @@
package com.spotify.app.category;

import com.spotify.app.dto.CategoryDTO;
import com.spotify.app.exception.DuplicateResourceException;
import com.spotify.app.exception.ResourceNotFoundException;
import com.spotify.app.mapper.CategoryMapper;
import com.spotify.app.mapper.CategoryResponseMapper;
import com.spotify.app.model.Category;
import com.spotify.app.repository.CategoryRepository;
import com.spotify.app.repository.PlaylistRepository;
import com.spotify.app.service.CategoryService;
import com.spotify.app.service.CloudinaryService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;

import java.lang.module.ResolutionException;
import java.util.Optional;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.any;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

@ExtendWith(MockitoExtension.class)
public class CategoryServiceTest {


@Mock
private CategoryRepository categoryRepository ;

@Mock
private CategoryResponseMapper categoryResponseMapper;
@Mock
private CategoryMapper categoryMapper;
@Mock
private PlaylistRepository playlistRepository;
@Mock
private CloudinaryService cloudinaryService;
private CategoryService underTest;

@BeforeEach
public void setUp () {
underTest = new CategoryService(categoryRepository, categoryResponseMapper, categoryMapper, playlistRepository, cloudinaryService );
}


@Test
public void canGetById () {
// given
Integer categoryId = 1;
Category expected = new Category(categoryId);

// when
Mockito.when(categoryRepository.findById(categoryId)).thenReturn(Optional.of(expected));
var actual = underTest.get(categoryId);

// then
assertThat(actual).isEqualTo(expected);
}

@Test
public void cannotGetByIdWitNotExistedId () {
// given
Integer categoryId = 1;

// when
Mockito.when(categoryRepository.findById(categoryId)).thenReturn(Optional.empty());


// then
assertThrows(ResourceNotFoundException.class, () -> {
underTest.get(categoryId);
});

Mockito.verify(categoryRepository, Mockito.times(1)).findById(categoryId);
}

@Test
public void canGetAllChildrenByParentCategory () {
// given
Integer categoryParentId = 1;
Category category = new Category(2);
Set<Category> categories = Set.of(category);
CategoryDTO categoryDTO = new CategoryDTO(2);
Set<CategoryDTO> expect = Set.of(categoryDTO);

// when
Mockito.when(categoryRepository.listAllChildByParenId(categoryParentId)).thenReturn(categories);
Mockito.when(categoryMapper.categoriesToCategoriesDTO(Mockito.any())).thenReturn(expect);

// then
var actual = underTest.listByParentId(categoryParentId);

assertThat(actual).isEqualTo(expect);
Mockito.verify(categoryRepository, Mockito.times(1)).listAllChildByParenId(categoryParentId);
Mockito.verify(categoryMapper, Mockito.times(1)).categoriesToCategoriesDTO(categories);
}

@Test
public void cannotAddCategoryWithTileExist () {
String title = "Test Category";
String parentTitle = "Parent Category";

// Mocking the CategoryRepository response
Mockito.when(categoryRepository.findByTitle(title)).thenReturn(Optional.of(new Category()));

// Calling the service method and expecting a DuplicateResourceException
assertThrows(DuplicateResourceException.class, () -> {
underTest.addCategory(title, parentTitle);
});

// Verifying that the repository method was called
Mockito.verify(categoryRepository, Mockito.times(1)).findByTitle(title);
Mockito.verify(categoryRepository, Mockito.never()).save(Mockito.any(Category.class));
}

@Test
public void canAddCategory() {
String title = "Test Category";

// Mocking the CategoryRepository response
Mockito.when(categoryRepository.findByTitle(title)).thenReturn(Optional.empty());
Mockito.when(categoryRepository.save(Mockito.any(Category.class))).thenAnswer(invocation -> invocation.getArgument(0));

// Calling the service method
underTest.addCategory(title, null);

// Verifying that the repository methods were called
Mockito.verify(categoryRepository, Mockito.times(1)).findByTitle(title);
Mockito.verify(categoryRepository, Mockito.times(1)).save(Mockito.any(Category.class));
}
@Test
public void cannotUpdateCategoryWithExistedCategoryTitle () {
Integer categoryId = 1;
String existingTitle = "Existing Category";
String newTitle = "New Category";
String categoryParentTitle = "Parent Category";

Category existingCategory = new Category();
existingCategory.setId(categoryId);
existingCategory.setTitle(existingTitle);

Mockito.when(categoryRepository.findById(categoryId)).thenReturn(Optional.of(existingCategory));
Mockito.when(categoryRepository.findByTitle(newTitle)).thenReturn(Optional.of(new Category()));

// Act and Assert
assertThrows(DuplicateResourceException.class, () ->
underTest.updateCategory(categoryId, newTitle, categoryParentTitle));

// Verify that save method is not called
Mockito.verify(categoryRepository, Mockito.never()).save(Mockito.any(Category.class));
}
@Test
public void testUpdateStatusCategory() {
// Sample data
Integer categoryId = 1;

// Mocking the CategoryRepository response
Category existingCategory = new Category();
existingCategory.setId(categoryId);
existingCategory.setStatus(true);
Mockito.when(categoryRepository.findById(categoryId)).thenReturn(Optional.of(existingCategory));
Mockito.when(categoryRepository.saveAndFlush(existingCategory)).thenAnswer(invocation -> invocation.getArgument(0));

// Calling the service method
String result = underTest.updateStatusCategory(categoryId);

// Verifying that the repository methods were called
Mockito.verify(categoryRepository, Mockito.times(1)).findById(categoryId);
Mockito.verify(categoryRepository, Mockito.times(1)).saveAndFlush(existingCategory);

// Verifying the result
String expectedStatusMessage = "category with id: 1 is enabled"; // Assuming initial status is true
assertEquals(expectedStatusMessage, result);
}

}

0 comments on commit 6558085

Please sign in to comment.