Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tests book category dev #16

Merged
merged 5 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package com.example.springbootbookshop.repository;

import com.example.springbootbookshop.entity.Order;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
Expand All @@ -14,5 +14,5 @@ public interface OrderRepository extends JpaRepository<Order, Long> {
Optional<Order> findOrderByIdAndUserId(Long orderId, Long userId);

@EntityGraph(attributePaths = {"user", "orderItems"})
Set<Order> findAllByUserId(Long userId, Pageable pageable);
List<Order> findAllByUserId(Long userId, Pageable pageable);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

import com.example.springbootbookshop.dto.book.BookDto;
import com.example.springbootbookshop.dto.book.CreateBookRequestDto;
import com.example.springbootbookshop.entity.Book;
import com.example.springbootbookshop.repository.BookRepository;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
Expand All @@ -30,7 +32,6 @@
import org.springframework.http.MediaType;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
Expand All @@ -43,11 +44,11 @@ public class BookControllerTest {
protected static MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private BookRepository bookRepository;

@BeforeAll
static void beforeAll(@Autowired WebApplicationContext applicationContext,
@Autowired DataSource dataSource) {
tearDown(dataSource);
static void beforeAll(@Autowired WebApplicationContext applicationContext) {
mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext)
.apply(springSecurity())
.build();
Expand Down Expand Up @@ -82,8 +83,6 @@ static void tearDown(DataSource dataSource) {

@Test
@DisplayName("Create a new book")
@Sql(scripts = "classpath:database/books/clear-books-db.sql",
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@WithMockUser(username = "admin", roles = {"ADMIN"})
void createBook_ValidRequestDto_Ok() throws Exception {
CreateBookRequestDto createBookRequestDto = new CreateBookRequestDto(
Expand Down Expand Up @@ -169,25 +168,20 @@ void getBookById_ValidId_Ok() throws Exception {
@Test
@DisplayName("Delete book by id")
@WithMockUser(username = "admin", roles = {"ADMIN","USER"})
void deleteBookById_ValidId_Ok() throws Exception {
void deleteBookByIdAssertSuccess() throws Exception {
mockMvc.perform(delete("/books/2")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());

MvcResult result = mockMvc.perform(get("/books")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();

List<BookDto> actualDtoList = objectMapper.readValue(result.getResponse()
.getContentAsString(), new TypeReference<>() {});
assertEquals(2, actualDtoList.size());
}

@Test
@DisplayName("Update book by id")
@WithMockUser(username = "admin", roles = {"ADMIN","USER"})
void updateBookById_ValidId_Ok() throws Exception {
Book bookFromDB = bookRepository.findById(2L).get();
assertNotNull(bookFromDB);
assertEquals("Book 2", bookFromDB.getTitle());

CreateBookRequestDto updatedDto = new CreateBookRequestDto(
"Updated Title", "Updated Author", "Updated ISBN",
BigDecimal.valueOf(29.99), "Updated Description", "updated.jpg",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ public class CategoryControllerTest {
private ObjectMapper objectMapper;

@BeforeAll
static void beforeAll(@Autowired WebApplicationContext applicationContext,
@Autowired DataSource dataSource) throws SQLException {
tearDown(dataSource);
static void beforeAll(@Autowired WebApplicationContext applicationContext) {
mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext)
.apply(springSecurity())
.build();
Expand Down Expand Up @@ -78,8 +76,6 @@ static void tearDown(DataSource dataSource) {

@Test
@DisplayName("Create a new category")
@Sql(scripts = "classpath:database/category/clear-category.sql",
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@WithMockUser(username = "admin", roles = {"ADMIN"})
void createNewCategory_ValidCategory_Ok() throws Exception {
CategoryRequestDto categoryRequestDto = new CategoryRequestDto(
Expand Down Expand Up @@ -127,21 +123,12 @@ void deleteCategoryById_ValidId_Ok() throws Exception {
mockMvc.perform(delete("/category/2")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());

MvcResult result = mockMvc.perform(get("/category")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();

CategoryDto[] actualDtoList = objectMapper.readValue(result.getResponse()
.getContentAsString(), CategoryDto[].class);
assertEquals(2, actualDtoList.length);
}

@Test
@DisplayName("User try delete category by id")
@WithMockUser(username = "user")
void deleteCategoryWithoutPermission_NotOk() throws Exception {
void deleteCategoryById_NoPermission_NotOk() throws Exception {
mockMvc.perform(delete("/category/2")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isForbidden());
Expand All @@ -150,15 +137,7 @@ void deleteCategoryWithoutPermission_NotOk() throws Exception {
@Test
@DisplayName("Update category by id")
@WithMockUser(username = "admin", roles = {"ADMIN","USER"})
void updateBookById_ValidId_Ok() throws Exception {
MvcResult result = mockMvc.perform(get("/category/2")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
CategoryDto dto = objectMapper.readValue(result.getResponse()
.getContentAsString(), CategoryDto.class);
assertEquals("Category 2", dto.name());

void updateCategoryById_ValidId_Ok() throws Exception {
CategoryRequestDto updateRequest = new CategoryRequestDto(
"Updated name",
"Updated description"
Expand Down Expand Up @@ -187,7 +166,7 @@ void updateBookById_ValidId_Ok() throws Exception {
@Sql(scripts = "classpath:database/books-categories/clear-book-category.sql",
executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@WithMockUser(username = "user")
void getBookByCategory_Ok() throws Exception {
void getAllBooksByCategory_Ok() throws Exception {
MvcResult result = mockMvc.perform(get("/category/2/books")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ void saveBook() {
Book book = bookMapper.toBook(dto);

when(bookRepository.save(any())).thenReturn(book);

BookDto savedDto = bookService.save(dto);

verify(bookRepository, times(1)).save(any());
Expand Down
Loading