Junit 5 +服务层FetchById方法中的Mockito从服务中检索返回null对象

slsn1g29  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(82)

我尝试使用Mockito在我的BookServiceTest中测试FetchById方法,但发生了此错误我使用的是JUnit 5和Mockito,在Sping Boot 版本3.1.3中随Sping Boot 启动器测试一起提供沿着
错误:

org.opentest4j.AssertionFailedError: expected: not <null>

    at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:152)
    at org.junit.jupiter.api.AssertionFailureBuilder.buildAndThrow(AssertionFailureBuilder.java:132)
    at org.junit.jupiter.api.AssertNotNull.failNull(AssertNotNull.java:49)
    at org.junit.jupiter.api.AssertNotNull.assertNotNull(AssertNotNull.java:35)
    at org.junit.jupiter.api.AssertNotNull.assertNotNull(AssertNotNull.java:30)
    at org.junit.jupiter.api.Assertions.assertNotNull(Assertions.java:301)
    at com.bookstore.com.serviceLevelTest.BookServTest.isFetchByIdValid(BookServTest.java:123)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:578)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)

下面是我的测试类:

@ExtendWith(MockitoExtension.class)
public class BookServTest {

    private static final Logger logger = LoggerFactory.getLogger(BookServTest.class);
    @Mock
    private BookRepository bookRepository;

    @Mock
    private ModelMappers modelMapper;
    @Mock
    AuthorService authorService;

    private BookService bookService;

    //Mock Object

    List<Book> bookDtos;
    private Book book;

    private BookDto bookDto;
    private Author author;

    @BeforeEach
    public void setUp(){
    bookService = new BookService(modelMapper,bookRepository,authorService);

        //Create BookDto
        bookDto = new BookDto();
        bookDto.setId(1L);
        bookDto.setTitle("The Usual Suspect");
        bookDto.setCategory("Crime");
        bookDto.setPrice(7800.55);
        bookDto.setAuthorName("Somxai");

        //Create Book
        book = new Book();
                book.setId(1L);
                book.setTitle("The Usual Suspect");
                book.setCategory("Crime");
                book.setPrice(7800.55);

        //Create list of bookDto
        bookDtos = new ArrayList<>();
        bookDtos.add(new Book(1L, "The Usual Suspect","Crime",7800.50));
        bookDtos.add(new Book(2L, "The Shutter Island","Crime",9000.50));
        bookDtos.add(new Book(3L, "The Shutter Island","Crime",9000.50));

        //Create Author
        author = new Author("Somxai","SSM","Laos PDR");

    }

//The error method:
 @Test
    void isFetchByIdValid(){
        //Arrange
        Mockito.when(bookRepository.fetchById(1L)).thenReturn(Optional.of(book)); //as i have checked this method is ok
        //Act
        BookDto bookDTO = bookService.fetchById(1L); // bookDTO return null
        //Assert
        Assertions.assertNotNull(bookDTO);

    }

//this method work fine
 @Test
    void isFetchAllValid(){
        //Arrange
        Pageable pageable = PageRequest.of(0,3,Sort.by("title").descending());
        Page<Book> expectedPage = new PageImpl<>(bookDtos, pageable, bookDtos.size());
        Mockito.when(bookRepository.findAll(pageable)).thenReturn(expectedPage);
        //Act
        List<BookDto> bookDtos1 = bookService.fetchAll(0,3,"title");
        //Assertion
        Assertions.assertNotNull(bookDtos1);
        Assertions.assertEquals(3,bookDtos1.size());
    }

以下是服务方法:

@Transactional
    @Cacheable(value = "book", key = "#id")
    public BookDto fetchById(Long id) {
        Optional<Book> book = bookRepository.fetchById(id);
        if (book.isEmpty()) {
            logger.info("book not found");
        }
        Book book1 = book.get();

        return modelMapper.bookToDTO(book1);
    }

下面是repository方法:

@Transactional
    @Query(value = "SELECT b FROM Book b JOIN FETCH b.author a WHERE b.id = :id")
    Optional<Book> fetchById(@Param("id") Long id);

下面是模型Map器的Map方法:

public BookDto bookToDTO(Book book){

            BookDto bookDto = new BookDto();
            bookDto = modelMapper().map(book, BookDto.class);
            if (book.getAuthor() != null){
                bookDto.setAuthorName(book.getAuthor().getFirstName() + " " + book.getAuthor().getLastName());
            }
            return bookDto;
        }

我一直在寻找一个类似的问题,并尝试了许多方法,但不适合我。注:当我在Postman中测试时,每个方法都工作正常。先谢了。

0h4hbjxa

0h4hbjxa1#

您在isFetchByIdValid测试中遇到的bookDTO为null的问题可能是由于模拟设置或modelMapper的使用方式存在问题。以下是故障排除和解决此问题的一些步骤:
1.确保bookRepository.fetchById(1L)模拟设置正确:
在你的测试中,你有这样一行:

Mockito.when(bookRepository.fetchById(1L)).thenReturn(Optional.of(book));

确保bookRepository被正确地模拟,并且fetchById方法被1L调用。另外,确保返回的book对象设置正确,并且不为null。
1.验证modelMapper
检查您的modelMapper配置并确保它正确地将Book实体Map到BookDto。问题可能在于modelMapper的设置方式或Map逻辑本身。
1.调试:
您可以向测试和服务方法添加一些调试语句,以帮助诊断问题。例如,您可以在测试中打印bookbook1bookDTO的值,以查看空值的来源。

@Test
void isFetchByIdValid() {
    // Arrange
    Mockito.when(bookRepository.fetchById(1L)).thenReturn(Optional.of(book));

    // Act
    BookDto bookDTO = bookService.fetchById(1L);

    // Debugging
    System.out.println("book: " + book);
    System.out.println("book1: " + book1);
    System.out.println("bookDTO: " + bookDTO);

    // Assert
    Assertions.assertNotNull(bookDTO);
}

在你的服务方法中,你可以添加日志语句来检查book是否被获取,以及到bookDTO的Map是否成功:

@Transactional
@Cacheable(value = "book", key = "#id")
public BookDto fetchById(Long id) {
    Optional<Book> book = bookRepository.fetchById(id);
    if (book.isEmpty()) {
        logger.info("Book not found");
    } else {
        logger.info("Book found: " + book.get()); // Log the book object
    }

    Book book1 = book.get();
    logger.info("Mapping book to bookDTO...");
    BookDto bookDTO = modelMapper.bookToDTO(book1);
    logger.info("Mapped book to bookDTO: " + bookDTO); // Log the bookDTO object

    return bookDTO;
}

这将帮助您确定问题发生的位置。
1.检查modelMapper配置:
确保modelMapper已正确配置为将Book实体Map到BookDto。仔细检查Map逻辑是否正确,并且它不会导致任何问题。
通过遵循这些步骤,您应该能够识别并解决导致bookDTO在测试中为null的问题。它可能与mock设置、modelMapper配置或如何在服务方法中执行Map有关。

i2byvkas

i2byvkas2#

太感谢你了!问题出在Map过程中这里是传递的代码。

@Test
void isFetchByIdValid(){
        Book bookSetup = new Book(1L,"Onepiece","Advanture",500.50);

        Optional<Book> optionalBook = Optional.of(bookSetup);

      // Arrange
        Mockito.when(bookRepository.fetchById(1L)).thenReturn(optionalBook);

        BookDto bookDto = new BookDto();
        bookDto.setId(bookSetup.getId());
        bookDto.setTitle(bookSetup.getTitle());
        bookDto.setCategory(bookSetup.getCategory());
        bookDto.setPrice(bookSetup.getPrice());

        Mockito.when(modelMapper.bookToDTO(bookSetup)).thenReturn(bookDto);
        // Act
        BookDto bookDTO = bookService.fetchById(1L);

        // Debugging
        System.out.println("book: " + bookSetup);
        System.out.println("bookDTO from service Test : " + bookDTO);
        System.out.println("BooDto from mapping: " + bookDto);

        // Assert
        Assertions.assertNotNull(bookDTO);

相关问题