我的其余api测试有问题。有人可以告诉我该怎么做吗?

完整代码在github上:https://github.com/kenez92/kodilla-library

此表达式返回null。为什么呢


BookDetailsDto bookDetailsDto = bookDetailsS​​ervice.findBookDetails(id);


@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class BookDetailsServiceTestSuite {
    @Mock
    private BookDetailsMapper bookDetailsMapper;
    @Mock
    private BookDetailsRepository bookDetailsRepository;
    @InjectMocks
    private BookDetailsService bookDetailsService;

    private BookDetails createBookDetails() {
        return BookDetails.builder()
                .id(1L)
                .code(1234L)
                .title("New Title")
                .author("New Author")
                .yearOfPublication(1999)
                .build();
    }

    @Test
    public void testGetBookDetailsById() {
        //Given
        long id = 1;
        Mockito.when(bookDetailsRepository.findById(id)).thenReturn(Optional.ofNullable(createBookDetails()));

        //When
        BookDetailsDto bookDetailsDto = bookDetailsService.findBookDetails(id);
        //Then
        Assert.assertEquals(bookDetailsDto.getId(), id);
        Assert.assertEquals(bookDetailsDto.getCode(), 1234L);
        Assert.assertEquals(bookDetailsDto.getTitle(), "New Title");
        Assert.assertEquals(bookDetailsDto.getAuthor(), "New Author");
        Assert.assertEquals(bookDetailsDto.getYearOfPublication(), 1999);
    }
}

最佳答案

这是findBookDetails的代码:

public BookDetailsDto findBookDetails(Long bookDetailsId) {
    log.debug("Find book details by id: {}", bookDetailsId);
    BookDetails bookDetails = bookDetailsRepository.findById(bookDetailsId)
            .orElseThrow(() -> new LibraryException(LibraryException.ERR_BOOK_DETAILS_NOT_FOUND_EXCEPTION));
    BookDetailsDto bookDetailsDto = bookDetailsMapper.mapToBookDetailsDto(bookDetails);
    log.debug("Book details found by id: {}", bookDetailsId);
    return bookDetailsDto;
}


您已经嘲笑了bookDetailsRepository.findById(id),但是还没有嘲笑BookDetailsDto bookDetailsDto = bookDetailsMapper.mapToBookDetailsDto(bookDetails);,这就是为什么它返回null的原因。

10-04 11:48