Skip to content

Commit

Permalink
Merge pull request #7 from neuefische/Feat/Edit-PUT-book
Browse files Browse the repository at this point in the history
Feat/edit put book
  • Loading branch information
marcelherr authored Aug 16, 2024
2 parents 896f955 + 08a5516 commit 62251b4
Show file tree
Hide file tree
Showing 13 changed files with 391 additions and 84 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.github.esgoet.backend.controllers;

import com.github.esgoet.backend.dto.NewBookDto;
import com.github.esgoet.backend.dto.BookDto;
import com.github.esgoet.backend.models.Book;
import com.github.esgoet.backend.services.BookService;
import lombok.RequiredArgsConstructor;
Expand All @@ -10,8 +10,10 @@
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;


import java.util.List;


@RestController
@RequestMapping("/api/books")
@RequiredArgsConstructor
Expand All @@ -36,7 +38,12 @@ public Book getBook(@PathVariable String id) {
}

@PostMapping
public Book addABook(@RequestBody NewBookDto newBookDto) {
return bookService.saveBook(newBookDto);
public Book addABook(@RequestBody BookDto bookDto) {
return bookService.saveBook(bookDto);
}

@PutMapping(path = {"{id}/update", "{id}"})
public Book update(@PathVariable String id, @RequestBody BookDto book) {
return bookService.updateBook(book, id);
}
}
18 changes: 18 additions & 0 deletions backend/src/main/java/com/github/esgoet/backend/dto/BookDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.github.esgoet.backend.dto;

import com.github.esgoet.backend.models.Genre;
import lombok.With;

import java.time.LocalDate;

@With
public record BookDto(
String author,
String title,
Genre genre,
String description,
String isbn,
String cover,
LocalDate publicationDate
) {
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ public record Book(
String author,
String title,
Genre genre,
String description,
String isbn,
String cover,
LocalDate publicationDate
) {
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.github.esgoet.backend.services;

import com.github.esgoet.backend.dto.NewBookDto;
import com.github.esgoet.backend.dto.BookDto;
import com.github.esgoet.backend.models.Book;
import com.github.esgoet.backend.models.BookNotFoundException;
import com.github.esgoet.backend.repositories.BookRepository;
Expand All @@ -9,7 +9,6 @@

import java.util.List;


@Service
@RequiredArgsConstructor
public class BookService {
Expand All @@ -30,14 +29,28 @@ public Book getBook(String id) {
.orElseThrow(() -> new BookNotFoundException("No book found with id: " + id));
}

public Book saveBook(NewBookDto newBookDto) {
public Book saveBook(BookDto bookDto) {
Book bookToSave = new Book(
idService.randomId(),
newBookDto.author(),
newBookDto.title(),
newBookDto.genre(),
newBookDto.publicationDate()
bookDto.author(),
bookDto.title(),
bookDto.genre(),
bookDto.description(),
bookDto.isbn(),
bookDto.cover(),
bookDto.publicationDate()
);
return bookRepository.save(bookToSave);
}

public Book updateBook(BookDto updateBook, String id) {
Book book = bookRepository.findById(id).orElseThrow(() -> new BookNotFoundException("No book found with id: " + id))
.withAuthor(updateBook.author())
.withCover(updateBook.cover())
.withDescription(updateBook.description())
.withGenre(updateBook.genre())
.withTitle(updateBook.title())
.withIsbn(updateBook.isbn());
return bookRepository.save(book);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.github.esgoet.backend.controllers;

import com.github.esgoet.backend.dto.BookDto;
import com.github.esgoet.backend.models.Book;
import com.github.esgoet.backend.models.Genre;
import com.github.esgoet.backend.repositories.BookRepository;
Expand All @@ -10,12 +11,15 @@
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

import java.time.LocalDate;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;


@SpringBootTest
@AutoConfigureMockMvc
Expand All @@ -41,44 +45,53 @@ public void getAllBooks_Test_When_DbEmpty_Then_returnEmptyArray() throws Excepti
@Test
void getBook_Test_whenIdExists() throws Exception {
//GIVEN
bookRepository.save(new Book("1","George Orwell", "1984", Genre.FANTASY, localDate));
bookRepository.save(new Book("1", "George Orwell", "1984", Genre.THRILLER, "this is a description", "123456isbn", "https://linkToCover", localDate));
//WHEN
mockMvc.perform(get("/api/books/1"))
//THEN
.andExpect(status().isOk())
.andExpect(content().json("""
{
"id": "1",
"author": "George Orwell",
"title": "1984",
"genre": "FANTASY",
"publicationDate": "2024-08-14"
"id": "1",
"author": "George Orwell",
"title": "1984",
"genre": "THRILLER",
"description": "this is a description",
"isbn": "123456isbn",
"cover": "https://linkToCover",
"publicationDate": "2024-08-14"
}
"""));
}

@Test
@DirtiesContext
void addABookTest_whenNewTodoExists_thenReturnNewTodo() throws Exception {
void addABookTest_whenNewBookExists_thenReturnNewBook() throws Exception {
// GIVEN

// WHEN
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{
"author": "Tolstoy",
"title": "War and Peace",
"genre": "HISTORY",
"publicationDate": "1869-01-01"
}
"""))
.contentType(MediaType.APPLICATION_JSON)
.content("""
{
"author": "Tolstoy",
"title": "War and Peace",
"genre": "HISTORY",
"description": "this is a description",
"isbn": "123456isbn",
"cover": "https://linkToCover",
"publicationDate": "1869-01-01"
}
"""))
// THEN
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").exists())
.andExpect(jsonPath("$.author").value("Tolstoy"))
.andExpect(jsonPath("$.title").value("War and Peace"))
.andExpect(jsonPath("$.genre").value("HISTORY"))
.andExpect(jsonPath("$.description").value("this is a description"))
.andExpect(jsonPath("$.isbn").value("123456isbn"))
.andExpect(jsonPath("$.cover").value("https://linkToCover"))
.andExpect(jsonPath("$.publicationDate").value("1869-01-01"));
}

Expand All @@ -101,7 +114,7 @@ void getBook_Test_whenIdDoesNotExists() throws Exception {
@Test
public void deleteBook() throws Exception {

bookRepository.save(new Book("1", "Simon", "HowToDeleteBooksFast", Genre.SCIENCE,localDate));
bookRepository.save(new Book("1", "Simon", "HowToDeleteBooksFast", Genre.SCIENCE, "description", "12345678", "https://linkToCover", localDate));

mockMvc.perform(delete("/api/books/1"))
.andExpect(status().isOk());
Expand All @@ -111,4 +124,38 @@ public void deleteBook() throws Exception {
.andExpect(content().json("[]"));
}

@DirtiesContext
@Test
void updateBook_Test_When_IdMatches() throws Exception {
// GIVEN
bookRepository.save(new Book("1", "author1", "title1", Genre.FANTASY, "description1", "12345678", "cover1", localDate));

// WHEN
mockMvc.perform(MockMvcRequestBuilders.put("/api/books/1/update")
.contentType("application/json")
.content("""
{
"author": "author2",
"title": "title2",
"genre": "HISTORY",
"description": "description2",
"isbn": "23456789",
"cover": "cover2",
"publicationDate": "2024-08-14"
}
"""))
// THEN
.andExpect(status().isOk())
.andExpect(content().json("""
{ "id": "1",
"author": "author2",
"title": "title2",
"genre": "HISTORY",
"description": "description2",
"isbn": "23456789",
"cover": "cover2",
"publicationDate": "2024-08-14"
}
"""));
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package com.github.esgoet.backend.services;

import com.github.esgoet.backend.dto.NewBookDto;
import com.github.esgoet.backend.dto.BookDto;
import com.github.esgoet.backend.models.Book;
import com.github.esgoet.backend.models.BookNotFoundException;
import com.github.esgoet.backend.models.Genre;
import com.github.esgoet.backend.repositories.BookRepository;
import org.junit.jupiter.api.Test;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -25,13 +26,13 @@ class BookServiceUnitTest {
@Test
void getAllBooks_Test() {
List<Book> allBooks = List.of(
new Book("1", "Simon", "Java for Dummies", Genre.SCIENCE, localDate),
new Book("2","Florian", "Java not for Dummies", Genre.SCIENCE, localDate)
new Book("1", "Simon", "Java for Dummies", Genre.HISTORY, "this is a description", "123456isbn", "https://linkToCover", localDate),
new Book("2", "Florian", "Java not for Dummies", Genre.THRILLER, "this is a description2", "789012isbn", "https://linkToAnotherCover", localDate)
);

List<Book> expectedBooks = List.of(
new Book("1", "Simon", "Java for Dummies", Genre.SCIENCE, localDate),
new Book("2","Florian", "Java not for Dummies", Genre.SCIENCE, localDate)
new Book("1", "Simon", "Java for Dummies", Genre.HISTORY, "this is a description", "123456isbn", "https://linkToCover", localDate),
new Book("2", "Florian", "Java not for Dummies", Genre.THRILLER, "this is a description2", "789012isbn", "https://linkToAnotherCover", localDate)
);

when(bookRepo.findAll()).thenReturn(allBooks);
Expand All @@ -52,12 +53,12 @@ void getAllBooks_WhenEmpty_ReturnsEmptyList() {
@Test
void getBook_Test_whenBookExists_thenReturnBook() {
//GIVEN
Book book = new Book("1", "George Orwell", "1984", Genre.FANTASY, localDate);
Book book = new Book("1", "George Orwell", "1984", Genre.THRILLER, "this is a description", "123456isbn", "https://linkToCover", localDate);
when(bookRepo.findById("1")).thenReturn(Optional.of(book));
//WHEN
Book actual = bookService.getBook("1");
//THEN
Book expected = new Book("1", "George Orwell", "1984", Genre.FANTASY, localDate);
Book expected = new Book("1", "George Orwell", "1984", Genre.THRILLER, "this is a description", "123456isbn", "https://linkToCover", localDate);
verify(bookRepo).findById("1");
assertEquals(expected, actual);
}
Expand All @@ -68,23 +69,23 @@ void getBook_Test_whenBookDoesNotExists_thenThrow() {
when(bookRepo.findById("1")).thenReturn(Optional.empty());
//WHEN
//THEN
assertThrows(BookNotFoundException.class,() -> bookService.getBook("1"));
assertThrows(BookNotFoundException.class, () -> bookService.getBook("1"));
verify(bookRepo).findById("1");
}

@Test
void addABookTest_whenNewBookAsInput_thenReturnNewBook() {
// GIVEN
NewBookDto newBookDto = new NewBookDto("J. K. Rowling", "Harry Potter", Genre.FANTASY, localDate);
Book bookToSave = new Book("1", newBookDto.author(), newBookDto.title(), newBookDto.genre(), newBookDto.publicationDate());
BookDto bookDto = new BookDto("J. K. Rowling", "Harry Potter", Genre.FANTASY, "this is a description", "123456isbn", "https://linkToCover", localDate);
Book bookToSave = new Book("1", bookDto.author(), bookDto.title(), bookDto.genre(), bookDto.description(), bookDto.isbn(), bookDto.cover(), bookDto.publicationDate());
when(bookRepo.save(bookToSave)).thenReturn(bookToSave);
when(idService.randomId()).thenReturn(bookToSave.id());

// WHEN
Book actual = bookService.saveBook(newBookDto);
Book actual = bookService.saveBook(bookDto);

// THEN
Book expected = new Book("1", newBookDto.author(), newBookDto.title(), newBookDto.genre(), newBookDto.publicationDate());
Book expected = new Book("1", bookDto.author(), bookDto.title(), bookDto.genre(), bookDto.description(), bookDto.isbn(), bookDto.cover(), bookDto.publicationDate());
verify(bookRepo).save(bookToSave);
verify(idService).randomId();
assertEquals(expected, actual);
Expand All @@ -96,4 +97,48 @@ void deleteBook_Test() {
bookService.deleteBook("1");
verify(bookRepo).deleteById("1");
}

@Test
void testUpdateBook_Success() {

// Given
String id = "1";
Book existingBook = new Book(id, "author1", "title1", Genre.THRILLER, "description1", "12345678", "cover1", localDate);
BookDto updatedBookDto = new BookDto("author2", "title2", Genre.FICTION, "description2", "23456789", "cover2", localDate);
Book updatedBook = new Book("1", "author2", "title2", Genre.FICTION, "description2", "23456789", "cover2", localDate);

// When
when(bookRepo.findById(id)).thenReturn(Optional.of(existingBook));
when(bookRepo.save(updatedBook)).thenReturn(updatedBook);

Book result = bookService.updateBook(updatedBookDto, id);

// Then
assertNotNull(result);
assertEquals(updatedBook, result);
verify(bookRepo).findById(id);
verify(bookRepo).save(updatedBook);
}

@Test
void testUpdateBook_BookNotFound() {

// Given
String id = "1";
BookDto updatedBookDto = new BookDto("author", "title", Genre.FICTION, "description", "isbn", "cover", localDate);
Book updatedBook = new Book("1", "author", "title", Genre.FICTION, "description", "isbn", "cover", localDate);

//When
when(bookRepo.findById(id)).thenReturn(Optional.empty());

//Then
BookNotFoundException thrown = assertThrows(
BookNotFoundException.class,
() -> bookService.updateBook(updatedBookDto, id)
);
assertEquals("No book found with id: " + id, thrown.getMessage());
verify(bookRepo).findById(id);
verify(bookRepo, never()).save(updatedBook);
}

}
Loading

0 comments on commit 62251b4

Please sign in to comment.