如何在单元测试中模拟JPA存储库的find方法

时间:2019-02-13 15:52:19

标签: java unit-testing spring-boot mockito junit5

我正在尝试使用我的小项目,但是我遇到了问题。 我的应用程序使用简单的分层体系结构,而我不能碰巧使用服务层。 实际上,我正在尝试从Spring数据模拟类 CrudRepository 。 我正在尝试对扩展此类的存储库之一的方法findAll进行模拟,但模拟不能模拟接口。 除了自己创建并填充Bean之外,还有其他方法吗?

[更新] 这是存储库代码:

package fr.kaf.interview.Repository;

import fr.kaf.interview.model.Book;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository extends CrudRepository<Book,Long> {
}

这里是UT:

@ExtendWith(MockitoExtension.class)
class BookServiceTest {


@Mock
private BookRepository bookRepository;

@InjectMocks
private BookService bookService;

@Test
public void should_get_All_books_from_database() {
    //Given

    Person author = new Person();
    author.setFirstName("Ka");
    author.setLastName("AwQl");

    Book firstBook = new Book();
    firstBook.setTitle("One Book");
    firstBook.setAuthors(singletonList(author));

    Book secondBook = new Book();
    secondBook.setTitle("Second Book");
    secondBook.setAuthors(singletonList(author));

    given(bookRepository.findAll()).willReturn(asList(firstBook, secondBook));

    //When
    List<Book> allBooks = bookService.getAllBooks();

    //Then
    assertThat(allBooks).containsExactly(firstBook, secondBook);

}

}

2 个答案:

答案 0 :(得分:0)

我想知道问题是否在于Mockito不确定如何将bookService注入Spring TestContext。

我会尝试按照《 JUnit5用户指南》“ Writing Tests Dependency Injection”部分底部的建议用@ExtendWith(SpringExtension.class)注释测试。

该注释的源代码为here

我还认为given BDD style of Mockitowhen\\then样式可能会有不同的结果。

答案 1 :(得分:0)

如果我还记得的话,您的测试必须使用此方法:

Ringtone ringtone = RingtoneManager.getRingtone(context, Settings.System.DEFAULT_RINGTONE_URI);