Skip to content
Snippets Groups Projects
Verified Commit 28ad3446 authored by Jan Kožusznik's avatar Jan Kožusznik
Browse files

LibraryServiceTest

parent 6c649138
No related merge requests found
package com.example.library;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class LibraryServiceTest {
@Mock
private BookRepository repository;
@InjectMocks
private LibraryService service;
@Captor
private ArgumentCaptor<Book> bookCaptor;
@Test
void borrowBook_shouldUpdateAvailabilityAndSave() {
// Arrange
Book book = new Book("Effective Java", "Joshua Bloch", true);
book.setAvailable(true);
when(repository.findById(1L)).thenReturn(Optional.of(book));
when(repository.save(any(Book.class))).thenAnswer(inv -> inv.getArgument(0));
// Act
boolean result = service.borrowBook(1L);
// Assert
assertTrue(result);
verify(repository).save(bookCaptor.capture());
Book savedBook = bookCaptor.getValue();
assertFalse(savedBook.isAvailable(), "Book should no longer be available after borrowing");
}
@Test
void returnBook_shouldUpdateAvailabilityAndSave() {
Book book = new Book("Domain-Driven Design", "Eric Evans", false);
when(repository.findById(2L)).thenReturn(Optional.of(book));
when(repository.save(any(Book.class))).thenAnswer(inv -> inv.getArgument(0));
boolean result = service.returnBook(2L);
assertTrue(result);
verify(repository).save(bookCaptor.capture());
Book savedBook = bookCaptor.getValue();
assertTrue(savedBook.isAvailable(), "Book should be available after return");
}
@Test
void borrowBook_shouldFail_whenBookNotFound() {
when(repository.findById(99L)).thenReturn(Optional.empty());
boolean result = service.borrowBook(99L);
assertFalse(result);
verify(repository, never()).save(any());
}
@Test
void returnBook_shouldFail_whenBookAlreadyAvailable() {
Book book = new Book("Clean Architecture", "Robert C. Martin", true);
when(repository.findById(3L)).thenReturn(Optional.of(book));
boolean result = service.returnBook(3L);
assertFalse(result);
verify(repository, never()).save(any());
}
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment