【问题标题】:How to mock JPA repository's find method in unit tests如何在单元测试中模拟 JPA 存储库的 find 方法
【发布时间】:2019-07-07 12:38:08
【问题描述】:

我正在尝试 UT 我的小项目,但我遇到了问题。 我的应用程序使用一个简单的分层架构,我不能碰巧在服务层上。 事实上,我正在尝试从 Spring-data 模拟类 CrudRepository。 我正在尝试模拟扩展此类的存储库之一的 findAll 方法,但 mockito 无法模拟接口。 除了自己创建 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);

}

}

【问题讨论】:

  • 您介意分享更多代码吗?比如你的 CrudRespository 和你的单元测试测试用例?
  • 当然是@Brandon,请在附件中找到代码
  • mockito 应该能够很好地模拟该界面 - 你得到什么异常?
  • @Janar:Mockito 无法模拟此类:接口 fr.test.repo.Repository.BookRepository。错误是这样的:“Mockito 只能模拟非私人和非最终课程。如果您不确定为什么会收到此错误,请向邮件列表报告。”
  • 您确定是 given(bookRepository.findAll()) 行引发了该异常吗? Find all 是一个非最终的公共方法,所以应该没问题。

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


【解决方案1】:

如果我记得你的测试必须使用这个:

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

【讨论】:

    【解决方案2】:

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

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

    该注解的源代码是here

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

    【讨论】:

      猜你喜欢
      • 2018-12-17
      • 2021-02-13
      • 1970-01-01
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 2014-06-25
      相关资源
      最近更新 更多