Skip to content

Commit

Permalink
Added tests for Book & Category service, minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
viacheslav-torbin committed Feb 2, 2024
1 parent 64535ea commit 62a43ab
Show file tree
Hide file tree
Showing 6 changed files with 214 additions and 54 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>1.18.0</version>
<version>1.19.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,6 @@ public record CreateBookRequestDto(
String description,
@Size(max = 255, message = "Maximum allowed size 255 characters")
String coverImage,
@NotNull
Set<Long> categoryIds) {
}
51 changes: 34 additions & 17 deletions src/test/java/org/bookstore/controller/BookControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ static void beforeAll(@Autowired WebApplicationContext applicationContext) {
"classpath:/scripts/books/delete-books.sql",
"classpath:/scripts/categories/create-categories.sql"
})
@WithMockUser(username = "admin", authorities = {"USER", "ADMIN"})
@WithMockUser(username = "admin", authorities = {"ADMIN"})
void createBook_validRequestDto_returnsDto() throws Exception {
CreateBookRequestDto request = new CreateBookRequestDto(
"title",
Expand All @@ -73,7 +73,7 @@ void createBook_validRequestDto_returnsDto() throws Exception {
);

MvcResult result = mockMvc.perform(post("/books")
.content(objectMapper.writeValueAsBytes(request))
.content(objectMapper.writeValueAsString(request))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated())
.andReturn();
Expand Down Expand Up @@ -151,7 +151,7 @@ void updateBookById_existingBook_BookDto() throws Exception {
);

MvcResult result = mockMvc.perform(put("/books/" + id)
.content(objectMapper.writeValueAsBytes(request))
.content(objectMapper.writeValueAsString(request))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
Expand All @@ -166,11 +166,34 @@ void updateBookById_existingBook_BookDto() throws Exception {
.hasFieldOrPropertyWithValue("coverImage", "image_changed");
}

@Test
@DisplayName("Create book with invalid request dto")
@Sql(scripts = {
"classpath:/scripts/books/delete-books.sql",
})
@WithMockUser(username = "admin", authorities = {"ADMIN"})
void createBook_invalidRequestDto_Exception() throws Exception {
CreateBookRequestDto request = new CreateBookRequestDto(
"title",
"author",
"12345678900",
BigDecimal.valueOf(-100),
"descr",
"image",
Set.of(1L)
);

mockMvc.perform(post("/books")
.content(objectMapper.writeValueAsString(request))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}

@Test
@DisplayName("Update non-existing book")
@WithMockUser(username = "admin", authorities = {"USER", "ADMIN"})
@Sql(scripts = "classpath:/scripts/books/delete-books.sql")
void updateBookById_nonExistingBook_exception() throws Exception {
void updateBookById_nonExistingBook_Exception() throws Exception {
long id = 1;
CreateBookRequestDto request = new CreateBookRequestDto(
"title",
Expand All @@ -183,28 +206,25 @@ void updateBookById_nonExistingBook_exception() throws Exception {
);

mockMvc.perform(put("/books/" + id)
.content(objectMapper.writeValueAsBytes(request))
.content(objectMapper.writeValueAsString(request))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound())
.andReturn();
.andExpect(status().isNotFound());
}

@Test
@DisplayName("Delete existing book")
@WithMockUser(username = "admin", authorities = {"USER", "ADMIN"})
void deleteById_existingBook_Ok() throws Exception {
mockMvc.perform(delete("/books/1"))
.andExpect(status().isNoContent())
.andReturn();
.andExpect(status().isNoContent());
}

@Test
@DisplayName("Find non existing book")
@WithMockUser(username = "admin", authorities = {"USER", "ADMIN"})
void findById_nonExistingBook_Exception() throws Exception {
mockMvc.perform(get("/books/100"))
.andExpect(status().isNotFound())
.andReturn();
.andExpect(status().isNotFound());
}

@Test
Expand All @@ -223,19 +243,16 @@ void updateById_nonExistingBook_Exception() throws Exception {
);

mockMvc.perform(put("/books/" + id)
.content(objectMapper.writeValueAsBytes(request))
.content(objectMapper.writeValueAsString(request))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound())
.andReturn();

.andExpect(status().isNotFound());
}

@Test
@DisplayName("Delete non existing book")
@WithMockUser(username = "admin", authorities = {"USER", "ADMIN"})
void deleteById_nonExistingBook_Exception() throws Exception {
mockMvc.perform(delete("/books/100"))
.andExpect(status().isNotFound())
.andReturn();
.andExpect(status().isNotFound());
}
}
18 changes: 7 additions & 11 deletions src/test/java/org/bookstore/controller/CategoryControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ void createCategory_validDto_CategoryDto() throws Exception {
);

MvcResult result = mockMvc.perform(post("/categories")
.content(objectMapper.writeValueAsBytes(request))
.content(objectMapper.writeValueAsString(request))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
Expand Down Expand Up @@ -122,7 +122,7 @@ void updateCategory_validDto_CategoryDto() throws Exception {
"some new scary text"
);
MvcResult result = mockMvc.perform(put("/categories/" + id)
.content(objectMapper.writeValueAsBytes(updateRequest))
.content(objectMapper.writeValueAsString(updateRequest))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
Expand All @@ -142,17 +142,15 @@ void updateCategory_validDto_CategoryDto() throws Exception {
@WithMockUser(username = "admin", authorities = {"USER", "ADMIN"})
void deleteById_existingBook_Ok() throws Exception {
mockMvc.perform(delete("/categories/1"))
.andExpect(status().isOk())
.andReturn();
.andExpect(status().isOk());
}

@Test
@DisplayName("Find non existing category")
@WithMockUser(username = "admin", authorities = {"USER", "ADMIN"})
void findById_nonExistingCategory_Exception() throws Exception {
mockMvc.perform(get("/categories/100"))
.andExpect(status().isNotFound())
.andReturn();
.andExpect(status().isNotFound());
}

@Test
Expand All @@ -166,18 +164,16 @@ void updateById_nonExistingCategory_Exception() throws Exception {
);

mockMvc.perform(put("/categories/" + id)
.content(objectMapper.writeValueAsBytes(request))
.content(objectMapper.writeValueAsString(request))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound())
.andReturn();
.andExpect(status().isNotFound());
}

@Test
@DisplayName("Delete non existing category")
@WithMockUser(username = "admin", authorities = {"USER", "ADMIN"})
void deleteById_nonExistingCategory_Exception() throws Exception {
mockMvc.perform(delete("/categories/100"))
.andExpect(status().isNotFound())
.andReturn();
.andExpect(status().isNotFound());
}
}
101 changes: 90 additions & 11 deletions src/test/java/org/bookstore/service/BookServiceTest.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package org.bookstore.service;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.when;

import java.math.BigDecimal;
import java.util.Optional;
import java.util.Set;
import org.bookstore.dto.book.BookDto;
import org.bookstore.dto.book.CreateBookRequestDto;
import org.bookstore.exceptions.EntityNotFoundException;
import org.bookstore.mapper.BookMapper;
import org.bookstore.mapper.impl.BookMapperImpl;
import org.bookstore.model.Book;
Expand Down Expand Up @@ -37,22 +40,13 @@ public class BookServiceTest {
private BookServiceImpl bookService;

@Test
@DisplayName("Save new book")
void saveBook_validBookDto_BookDto() {
@DisplayName("Save valid book")
void save_validRequestDto_BookDto() {
Category category = new Category();
category.setId(1L);
category.setName("name");
category.setDescription("desc");

Book book = new Book();
book.setAuthor("author");
book.setTitle("title");
book.setCategories(Set.of(category));
book.setIsbn("isbn-000001");
book.setPrice(BigDecimal.TEN);
book.setDescription("descr");
book.setCoverImage("image");

CreateBookRequestDto request = new CreateBookRequestDto(
"title",
"author",
Expand All @@ -63,6 +57,15 @@ void saveBook_validBookDto_BookDto() {
Set.of(1L)
);

Book book = new Book();
book.setAuthor(request.author());
book.setTitle(request.title());
book.setCategories(Set.of(category));
book.setIsbn(request.isbn());
book.setPrice(request.price());
book.setDescription(request.description());
book.setCoverImage(request.coverImage());

when(bookRepository.save(book)).thenReturn(book);
when(bookMapper.toEntity(request)).thenReturn(book);
when(categoryRepository.getReferenceById(1L)).thenReturn(category);
Expand All @@ -76,4 +79,80 @@ void saveBook_validBookDto_BookDto() {
.hasFieldOrPropertyWithValue("coverImage", request.coverImage())
.hasFieldOrPropertyWithValue("categoriesIds", request.categoryIds());
}

@Test
@DisplayName("Get book with valid id")
void getBookById_validId_BookDto() {
Book book = new Book();
book.setId(1L);
book.setAuthor("Author");
book.setTitle("Title");
book.setIsbn("553322");
book.setPrice(BigDecimal.valueOf(125.55));
book.setDescription("some desc");
book.setCoverImage("some url");

when(bookRepository.findById(1L)).thenReturn(Optional.of(book));

BookDto actual = bookService.findById(1L);

assertThat(actual)
.hasFieldOrPropertyWithValue("id", book.getId())
.hasFieldOrPropertyWithValue("title", book.getTitle())
.hasFieldOrPropertyWithValue("author", book.getAuthor())
.hasFieldOrPropertyWithValue("price", book.getPrice())
.hasFieldOrPropertyWithValue("description", book.getDescription())
.hasFieldOrPropertyWithValue("coverImage", book.getCoverImage());
}

@Test
@DisplayName("Get book with not existing id")
void getBookById_notValidId_Exception() {
Long id = 100L;
when(bookRepository.findById(id)).thenReturn(Optional.empty());

assertThatThrownBy(() -> bookService.findById(id))
.isInstanceOf(EntityNotFoundException.class);
}

@Test
@DisplayName("Update existing book with valid request")
void updateBook_validRequestDto_BookDto() {
Long id = 1L;
CreateBookRequestDto requestDto = new CreateBookRequestDto(
"Title",
"Author",
"553322",
BigDecimal.valueOf(125.55),
"some desc",
"some url",
Set.of(id));

Category category = new Category();
category.setId(id);

Book book = new Book();
book.setId(id);
book.setAuthor(requestDto.author());
book.setTitle(requestDto.title());
book.setIsbn(requestDto.isbn());
book.setPrice(requestDto.price());
book.setDescription(requestDto.description());
book.setCoverImage(requestDto.coverImage());
book.setCategories(Set.of(category));

when(bookRepository.findById(id)).thenReturn(Optional.of(book));
when(bookRepository.save(book)).thenReturn(book);

BookDto actual = bookService.updateBookById(id, requestDto);

assertThat(actual)
.hasFieldOrPropertyWithValue("id", id)
.hasFieldOrPropertyWithValue("title", requestDto.title())
.hasFieldOrPropertyWithValue("author", requestDto.author())
.hasFieldOrPropertyWithValue("price", requestDto.price())
.hasFieldOrPropertyWithValue("description", requestDto.description())
.hasFieldOrPropertyWithValue("coverImage", requestDto.coverImage())
.hasFieldOrPropertyWithValue("categoriesIds", requestDto.categoryIds());
}
}
Loading

0 comments on commit 62a43ab

Please sign in to comment.