You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JUnit 5+Mockito测试BookService的fetchById方法返回null问题

问题:Spring Boot 3.1.3中JUnit 5+Mockito测试BookService.fetchById时断言失败(返回null)

错误信息

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;

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

    // 报错的测试方法
    @Test
    void isFetchByIdValid(){
        //Arrange
        Mockito.when(bookRepository.fetchById(1L)).thenReturn(Optional.of(book)); 
        //Act
        BookDto bookDTO = bookService.fetchById(1L); // 返回null
        //Assert
        Assertions.assertNotNull(bookDTO);
    }

    // 正常工作的测试方法
    @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());
    }
}

Service层fetchById代码

@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层fetchById代码

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

ModelMapper映射方法代码

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

问题说明

测试中已Mock bookRepository.fetchById(1L) 返回 Optional.of(book),但调用 bookService.fetchById(1L) 返回null导致断言失败;fetchAll 测试正常,Postman接口测试所有方法均正常。


解决方案

问题核心是**modelMapper是Mockito生成的Mock对象,默认所有方法返回null**,你没有对modelMapper.bookToDTO(book)的返回值做Mock配置,导致Service层调用该方法时得到null。

修改isFetchByIdValid测试方法,在Arrange阶段添加对modelMapper的Mock:

@Test
void isFetchByIdValid(){
    //Arrange
    Mockito.when(bookRepository.fetchById(1L)).thenReturn(Optional.of(book));
    // 新增:指定modelMapper转换目标Book时返回预设的bookDto
    Mockito.when(modelMapper.bookToDTO(book)).thenReturn(bookDto);
    //Act
    BookDto bookDTO = bookService.fetchById(1L);
    //Assert
    Assertions.assertNotNull(bookDTO);
    // 可选:添加字段断言,验证转换结果正确性
    Assertions.assertEquals("The Usual Suspect", bookDTO.getTitle());
}

为什么fetchAll测试正常?

推测fetchAll方法中使用的modelMapper批量转换逻辑(比如重载的批量转换方法)在测试中被正确Mock,或者该方法未对转换结果做非空断言,因此未触发错误。


内容的提问来源于stack exchange,提问作者Xai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 12:38:10