jeudi 28 janvier 2021

How to mock required related entity?

In my problem I want to test PostService class. Every new added post have to have Book (entity) assigned to it first. There is relation OneToMany (one book can have many posts). So if you want to add new post it will be like:

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

So my savePost method is:

@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);
}

Now I want to test this method. How can I mock Book inside Post without inject bookRepository/bookService and without really saving it? Book is also nested (have categories, authors etc.) so it will be hard to make if from 0 every time. I tried something like this:

    @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(); ...

But it is obviously wrong. What should I do?

Aucun commentaire:

Enregistrer un commentaire