Skip to content
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
53 changes: 51 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
<maven.checkstyle.plugin.configLocation>checkstyle.xml</maven.checkstyle.plugin.configLocation>
<mapstruct.version>1.5.5.Final</mapstruct.version>
<lombok.mapstruct.binding.version>0.2.0</lombok.mapstruct.binding.version>
<testcontainers.version>1.21.3</testcontainers.version>
</properties>

<dependencies>
Expand Down Expand Up @@ -147,8 +148,45 @@
<artifactId>spring-boot-docker-compose</artifactId>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mysql</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>7.0.2</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.20.0</version>
<scope>test</scope>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>${testcontainers.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>

Expand Down Expand Up @@ -177,8 +215,8 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<source>19</source>
<target>19</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
Expand Down Expand Up @@ -209,6 +247,17 @@
<artifactId>liquibase-maven-plugin</artifactId>
<version>${liquibase.version}</version>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<argLine>
-javaagent:${settings.localRepository}/org/mockito/mockito-core/5.20.0/mockito-core-5.20.0.jar
</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public ResponseEntity<CategoryDto> createCategory(
@GetMapping
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
@Operation(summary = "Get all categories", description = "Fetch all categories")
public ResponseEntity<List<CategoryDto>> getAll() {
public ResponseEntity<List<CategoryDto>> getAllCategories() {
return new ResponseEntity<List<CategoryDto>>(
categoryService.findAll(),
HttpStatus.OK
Expand All @@ -56,7 +56,7 @@ public ResponseEntity<List<CategoryDto>> getAll() {
@Operation(summary = "Get a category by ID", description = "Get a category with specified ID")
public ResponseEntity<CategoryDto> getCategoryById(@PathVariable Long id) {
return new ResponseEntity<CategoryDto>(
categoryService.getById(id),
categoryService.findById(id),
HttpStatus.OK
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
public interface CategoryService {
List<CategoryDto> findAll();

CategoryDto getById(Long id);
CategoryDto findById(Long id);

CategoryDto save(CreateCategoryRequestDto createCategoryRequestDto);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public List<CategoryDto> findAll() {
}

@Override
public CategoryDto getById(Long id) {
public CategoryDto findById(Long id) {
Category category = categoryRepository.findById(id)
.orElseThrow(
() -> new EntityNotFoundException("Category with id ["
Expand All @@ -50,8 +50,8 @@ public CategoryDto save(CreateCategoryRequestDto createCategoryRequestDto) {
public CategoryDto update(Long id, CreateCategoryRequestDto changedCategoryDto) {
Category existingCategory = categoryRepository.findById(id)
.orElseThrow(
() -> new EntityNotFoundException("Category with id: "
+ id + " not found!"));
() -> new EntityNotFoundException("Category with id ["
+ id + "] not found!"));

categoryMapper.updateCategoryFromDto(changedCategoryDto, existingCategory);
categoryRepository.save(existingCategory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import jakarta.validation.ConstraintValidatorContext;

public class TitleValidator implements ConstraintValidator<Title, String> {
private static final int MINIMUM_TITLE_LENGTH = 8;
private static final int MINIMUM_TITLE_LENGTH = 4;

@Override
public boolean isValid(String title, ConstraintValidatorContext constraintValidatorContext) {
Expand Down
33 changes: 33 additions & 0 deletions src/test/java/com/springm/store/config/CustomContainer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.springm.store.config;

import org.testcontainers.containers.MySQLContainer;

public class CustomContainer extends MySQLContainer<CustomContainer> {
private static final String DB_IMAGE = "mysql:9.5.0";

private static CustomContainer container;

private CustomContainer() {
super(DB_IMAGE);
}

public static synchronized CustomContainer getInstance() {
if (container == null) {
container = new CustomContainer();
}
return container;
}

@Override
public void start() {
super.start();
System.setProperty("TEST_DB_URL", container.getJdbcUrl());
System.setProperty("TEST_DB_USERNAME", container.getUsername());
System.setProperty("TEST_DB_PASSWORD", container.getPassword());
}

@Override
public void stop() {
super.stop();
}
}
170 changes: 170 additions & 0 deletions src/test/java/com/springm/store/controller/BookControllerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package com.springm.store.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springm.store.dto.book.BookDto;
import com.springm.store.dto.book.CreateBookRequestDto;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
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.http.MediaType;
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 static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.testcontainers.shaded.org.apache.commons.lang3.builder.EqualsBuilder.reflectionEquals;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@WithMockUser(username = "admin", roles = {"ADMIN"})
@Sql(scripts = {"classpath:database/books/add-items-to-categories-table.sql",
"classpath:database/books/add-three-items-to-books-table.sql",
"classpath:database/books/assign-categories-for-books.sql"})
@Sql(scripts = "classpath:database/books/clear-all-tables.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
class BookControllerTest {
@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper;

@Test
@DisplayName("Add a new book")
void createBook_ValidRequestDto_Success() throws Exception {

CreateBookRequestDto bookRequestDto = new CreateBookRequestDto();
bookRequestDto.setTitle("Dune");
bookRequestDto.setAuthor("Frank Gerbert");
bookRequestDto.setIsbn("978-0316597011");
bookRequestDto.setPrice(BigDecimal.valueOf(35.32));
bookRequestDto.setCategoryIds(Set.of(1L));

BookDto expected = new BookDto();
expected.setTitle(bookRequestDto.getTitle());
expected.setAuthor(bookRequestDto.getAuthor());
expected.setIsbn(bookRequestDto.getIsbn());
expected.setPrice(bookRequestDto.getPrice());
expected.setCategoryIds(bookRequestDto.getCategoryIds());

String jsonRequest = objectMapper.writeValueAsString(bookRequestDto);

MvcResult result = mockMvc.perform(
post("/books")
.content(jsonRequest)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(status().isCreated())
.andReturn();

BookDto actual = objectMapper.readValue(result.getResponse().getContentAsString(), BookDto.class);

assertTrue(
reflectionEquals(expected, actual, "id")
);
}

@Test
@DisplayName("Find all available books")
void findAll_ValidItems_ShouldReturnAllBooks() throws Exception {
MvcResult result = mockMvc.perform(get("/books")
.param("page", "0")
.param("size", "4")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
int expectedElementsCount = 3;
String jsonResponse = result.getResponse().getContentAsString();

Map<String, Object> responseMap = objectMapper.readValue(
jsonResponse,
new TypeReference<>() {
});
List<BookDto> actualList = objectMapper.convertValue(
responseMap.get("content"),
new TypeReference<List<BookDto>>() {
}
);

assertThat(actualList)
.extracting(BookDto::getTitle)
.containsExactly("Kobzar", "Harry Potter", "The Witcher");
assertEquals(expectedElementsCount, responseMap.get("totalElements"));
assertEquals(expectedElementsCount, ((List<?>) responseMap.get("content")).size());
}

@Test
@DisplayName("Returns book with right id")
void getBookById_ValidItems_ShouldReturnBook() throws Exception {
MvcResult result = mockMvc.perform(
get("/books/1")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();

String jsonResponse = result.getResponse().getContentAsString();

assertTrue(jsonResponse.contains("Kobzar"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

compare expected and actual dto

assertTrue(jsonResponse.contains("Taras Shevchenko"));
assertTrue(jsonResponse.contains("978-1909156548"));
}

@Test
@DisplayName("Updates book by id")
void updateBookById_ValidInput_Success() throws Exception {
CreateBookRequestDto bookRequestDto = new CreateBookRequestDto();
bookRequestDto.setTitle("The World of Ice and Fire");
bookRequestDto.setAuthor("George R. R. Martin");
bookRequestDto.setIsbn("978-0316597101");
bookRequestDto.setPrice(BigDecimal.valueOf(69.99));
bookRequestDto.setCategoryIds(Set.of(1L, 2L));

String jsonRequest = objectMapper.writeValueAsString(bookRequestDto);

MvcResult result = mockMvc.perform(
put("/books/2")
.content(jsonRequest)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();

BookDto actual = objectMapper.readValue(
result.getResponse().getContentAsString(),
BookDto.class
);

BookDto expected = new BookDto();
expected.setId(2L);
expected.setTitle(bookRequestDto.getTitle());
expected.setAuthor(bookRequestDto.getAuthor());
expected.setIsbn(bookRequestDto.getIsbn());
expected.setPrice(bookRequestDto.getPrice());
expected.setCategoryIds(bookRequestDto.getCategoryIds());

assertTrue(reflectionEquals(expected, actual, "id"));
}

@Test
@DisplayName("Deletes book by id")
void deleteBookById_ValidInput_Success() throws Exception {
mockMvc.perform(
delete("/books/3")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
}
}
Loading