BookServiceOldTest.java 1.54 KB
package org.legrog.web.book;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.legrog.entities.Book;
import org.legrog.web.book.BookServiceOld;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;
import java.util.Arrays;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;


@RunWith(MockitoJUnitRunner.class)
public class BookServiceOldTest {

    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    private EntityManager entityManager;

    private BookServiceOld bookServiceOld;

    @Before
    public void setUp() {
        bookServiceOld = new BookServiceOld(entityManager);
    }

    @Test
    public void testAddBook() {
        Book book = new Book();
        bookServiceOld.addBook(book);
        Mockito.verify(entityManager).persist(book);
    }


    @Test
    public void testAllBooks() {

        Book book = new Book();
        book.setBookId(0);

        CriteriaQuery<Book> cq = Mockito.mock(CriteriaQuery.class);
        Mockito.when(entityManager.getCriteriaBuilder().createQuery(Book.class))
                .thenReturn(cq);
        Mockito.when(entityManager.createQuery(cq).getResultList())
                .thenReturn(Arrays.asList(book));

        List<Book> allBooks = bookServiceOld.getAllBooks();

        assertThat(allBooks).as("book list")
                .hasSize(1)
                .contains(book);

    }
}