Junit 5 + Mockito 在服务层 FetchById 方法从服务检索返回空对象

问题描述 投票:0回答:1

我尝试使用 Mockito 测试 BookServiceTest 中的 FetchById 方法,但发生了此错误 我正在使用 JUnit 5 和 Mockito,它们在 Spring Boot 版本 3.1.3 中随 Spring Boot Starter 测试一起提供

错误:

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

这是存储库方法:



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



我一直在寻找类似的问题并尝试了很多方法但对我不起作用 预先感谢。

java spring-boot unit-testing mockito junit5
1个回答
0
投票

您在

bookDTO
测试中遇到
isFetchByIdValid
为空的问题可能是由于您的模拟设置或
modelMapper
的使用方式存在问题。以下是排除和解决问题的一些步骤:

  1. 确保

    bookRepository.fetchById(1L)
    模拟设置正确:

    在您的测试中,您有这一行:

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

    确保

    bookRepository
    已正确模拟,并且使用
    fetchById
    调用
    1L
    方法。另外,请确保返回的
    book
    对象已正确设置且不为 null。

  2. 验证

    modelMapper

    检查您的

    modelMapper
    配置并确保其将
    Book
    实体正确映射到
    BookDto
    。问题可能在于
    modelMapper
    的设置方式或映射逻辑本身。

  3. 调试:

    您可以在测试和服务方法中添加一些调试语句来帮助诊断问题。例如,您可以在测试中打印

    book
    book1
    bookDTO
    的值,以查看空值来自何处。

    @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
    是否成功:

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

    这应该可以帮助您查明问题发生的位置。

  4. 检查

    modelMapper
    配置:

    确保正确配置

    modelMapper
    以将
    Book
    实体映射到
    BookDto
    。仔细检查映射逻辑是否正确并且不会导致任何问题。

通过执行这些步骤,您应该能够识别并解决导致测试中

bookDTO
为空的问题。它可能与模拟设置、
modelMapper
配置或如何在服务方法中执行映射有关。

© www.soinside.com 2019 - 2024. All rights reserved.