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

测试CustomerService的createCustomer方法时出现NullPointerException排查

问题根源与解决方案

为什么会抛出NullPointerException?

你遇到的空指针异常根本原因是测试类中的underTest(CustomerService实例)未被正确初始化,处于null状态,调用underTest.createCustomer(customer)时自然触发异常。

具体原因分析

  1. 错误的注入注解:你给CustomerService underTest用了@Autowired注解,但当前测试基于MockitoExtension.class运行,没有启动Spring容器,Spring的依赖注入机制不会生效,导致underTest始终为null。
  2. 关于JUnit4/JUnit5混用的疑问:你提到的when()方法属于Mockito的API,并非JUnit4专属,只要引入适配JUnit5的Mockito依赖(如mockito-junit-jupiter),完全可以在JUnit5环境下正常使用,这不是引发空指针的原因。

修复方案

1. 替换注入注解

把测试类中的@Autowired换成Mockito提供的@InjectMocks注解,它会自动创建CustomerService实例,并将标注@Mock的CustomerRepository注入进去:

@ExtendWith(MockitoExtension.class)
class CustomerServiceTest {

    @Mock
    CustomerRepository customerRepository;
    @InjectMocks // 替换原有的@Autowired
    private CustomerService underTest;

    @Test
    void canCreateCustomer() {
        // given
        Customer customer = new Customer(1,"Firstname", "Lastname", "0987654321", "email@domain.com", "password", ZonedDateTime.now());

        Mockito.lenient().when(customerRepository.existsByEmailId(anyString())).thenReturn(false);
        Mockito.lenient().when(customerRepository.existsByPhoneNumber(anyString())).thenReturn(false);
        Mockito.lenient().when(customerRepository.save(any(Customer.class))).thenReturn(customer);

        // when
        ResponseEntity<Customer> fetchedCustomer = underTest.createCustomer(customer);

        // then
        assertEquals(ResponseEntity.ok(customer), fetchedCustomer);
    }
}

2. 调整测试注释顺序(可选)

按照BDD测试风格调整注释顺序(given→when→then),提升代码可读性,这一步不影响功能,但能让测试逻辑更清晰。

3. 确保依赖正确

如果用Maven,确保pom.xml中引入的是适配JUnit5的Mockito依赖,而非旧的JUnit4版本:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>4.0.0</version> <!-- 使用最新稳定版即可 -->
    <scope>test</scope>
</dependency>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:10:28