Spring Boot, Tests: Mock inside nested functions

16 views Asked by At

is it possible - and if so, could someone provide me with an example - to mock a certain nested part of a service and use it inside a test later on? For example I have two services:

AuthorService.java:

public Author getByAuthorId(final String authorId) {
    return authorRepository.findByAuthorId(authorId).orElseThrow(()
            -> new ExampleException("Cannot find author by author id "+ authorId));
}

This function inside the AuthorService get's called inside my next Service...

BookService.java:

public Book getBook(final String name) {
    return bookRepository.findByName(name).orElseThrow(() -> new ExampleException("Cannot find book by " + name));
}

public Book getBookByAuthorId(String authorId) {
    Author author = authorService.getByAuthorId(authorId);  // <--- I want this author to be mocked...
    return getBook(author.getName());
}

Now I want to test the function getBookByAuthorId and mock the author that get's returned and use it with the also included getBook:

BookServiceTest.java:

@SpringBootTest
@AutoConfigureMockMvc
@Testcontainers
public class BookServiceTest extends AbstractContainerBaseTest {

    @Autowired
    private AuthorService authorService;

    @Autowired
    private BookService bookService;

    private Author author_mocked = new Author(
        1,  // id
        "John Doe"  // name
    );

    @Test
    @DisplayName("Book- get book by author id")
    public void testBookGetBookByAuthorId() {
        // here I want to mock the nested function 'getByAuthorId' that get's used inside of 'getBookByAuthorId'
        when(authorService.getByAuthorId(anyString())).thenReturn(author_mocked);
        Book book = bookService.getBookByAuthorId("42");
        Assertions.assertEquals("Example book title", book.getTitle());
    }
}

Is this even possible or do I miss something very important here? Thanks for all your help in regard and have a great day!

0

There are 0 answers