如何模拟所需的相关实体?

axzmvihb  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(332)

在我的问题中,我想测试一下售后服务类。每一个新增加的职位必须有书(实体)分配给它第一。一本书可以有很多帖子。因此,如果您想添加新的帖子,它将是这样的:

post: {
   "title": "postTitle1",
   "content": "Content of post",
   "bookId": "1"
}

所以我的savepost方法是:

@Transactional
public Post savePost(Post post) {
    Optional<Book> bookOpt = Optional.ofNullable(post.getBook());
    Book bookInPost = bookOpt.orElseThrow(() -> new IllegalArgumentException("Book id for new Post cannot be null!"));
    Book book = bookService.getBook(bookInPost.getId());
    book.addPost(post);
    return postRepository.save(post);
}

现在我想测试一下这个方法。我怎样才能在没有注入bookrepository/bookservice和没有真正保存它的情况下在post中模拟图书呢?这本书也是嵌套的(有类别,作者等),所以它将很难使如果从0每一次。我试过这样的方法:

@Test
    void should_save_post_assigned_to_book() {
        //given
        Post post = new Post("Title 1", "Content 1");
        Book bookToReturnFromRepository = new Book();
        bookToReturnFromRepository.setId(2);
        //when
        when(mockedBookRepository.findById(any())).thenReturn(Optional.of(bookToReturnFromRepository));
        postService.savePost(post);
        //then
        Optional<Post> loaded = postRepository.findById(post.getId());
        assertAll(() -> {
            assertThat(loaded).isPresent(); ...

但这显然是错误的。我该怎么办?

z2acfund

z2acfund1#

你必须首先确定你需要测试什么。测试时 savePost 有两个分支:一个是post没有book,方法trows exception;另一个是post保存了所有信息。
考虑到这一点,第一个测试将是 verify 当接收到不完整的post时抛出异常。在这里也将很好地验证没有保存任何内容( postRepository.save() (从未调用)
对于第二个测试,您需要验证 book.addPost() 我打过电话 postRepository.save(post) 是用最初的帖子打电话来的。
尽管如此,对于 postRepository 是必不可少的。假设您正在使用mockito或类似的工具:

@Test(expected = IllegalArgumentException.class)
public void postWithoutBook() {

    // Given a post that doesn't have a book
    final Post post = mock(Post.class);
    when(post.getBook()).thenReturn(null);

    // When trying to save it, we expect an exception to be thrown.
    realPostRepository.savePost(post);

    verify(mockedPostRepository, never()).save(any());
}

@Test
public void postWithBook() {
    // Given a post that does have a book
    final Book book = mock(Book);
    final Post post = mock(Post.class);
    when(post.getBook()).thenReturn(book);

    // When trying to save it...
    realPostRepository.savePost(post);

    // We expect it to be saved.
    verify(mockedPostRepository, times(1)).save(post);
    // And assigned  to a book
    verify(book, times(1)).addPost(post);
}

相关问题