public class BookControllerTest {
int ID=2;
int RELEASE=22;
String AUTHOR="HOMERO";
String TITLE="LA ODISEA";
Book BOOK = new Book();
Optional<Book> OPTIONAL_BOOK = Optional.of(BOOK);
List<Review>REVIEW_LIST = new ArrayList<>();
Optional<Book> OPTIONAL_BOOK_EMPTY = Optional.empty();
/*Optional<Book> OPTIONAL_BOOK_DELETE = Optional.deleted();->error*/
@Mock
private BookRepository bookRepository;
@InjectMocks
private BookController bookController;
...
@Test
public void testDeleteBook() {
Mockito.when(bookRepository.findById(ID)).thenReturn(OPTIONAL_BOOK_DELETE);
ResponseEntity<Object> httpresponse = bookController.deleteBook(ID);
assertEquals(HttpStatus.OK, httpresponse.getStatusCode());
}
@Test
public void testDeleteBookNotFound() {
Mockito.when(bookRepository.findById(ID)).thenReturn(OPTIONAL_BOOK_EMPTY);
ResponseEntity<Object> httpresponse = bookController.deleteBook(ID);
assertEquals(HttpStatus.NOT_FOUND, httpresponse.getStatusCode());
}
}
I am new to this, would you be very kind, where is the error or what is the correct way?, I thought I could do the same as the empty method but I tried all the reserved words but it didn't work for me
Optionalis a SDK class introduced with Java 8 and defines a fixed set of methods (cf. JavaDoc). You cannot "invent" your own methods on it and expect them to magically work.java.util.Optionalis in no way dependent on your services.If you have an optional without value, that's
Optional.empty(). If you have an optional with a value, that'sOptional.of(…). So deleting a book would still useOptional.empty(). Same as yourbookNotFoundtest usesOptional.empty()and notOptional.notFound().(Answer too long for a comment, but I'd rather have this question closed as "typo".)