测试REST API

I have problem with test for my rest api. Can anybody tell me how can I do that ? full code on 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);
    }
}
评论
fharum
fharum

这是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;
}

You have mocked bookDetailsRepository.findById(id) but you haven't mocked BookDetailsDto bookDetailsDto = bookDetailsMapper.mapToBookDetailsDto(bookDetails);, that's why it returns null.

点赞
评论