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

为JPAQueryFactory编写单元测试时遭遇空指针异常

问题分析

单元测试抛出空指针的原因是:你通过Mockito创建的JPAQueryFactory mock对象,在调用update()方法时默认返回null,后续链式调用where()、set()、execute()时,会因空对象调用方法触发空指针异常。

解决方案

需要为JPAQueryFactory的链式调用步骤逐一mock返回值,保证每个方法调用都能得到非空对象以继续执行后续操作:

修改后的测试代码如下:

@ExtendWith(MockitoExtension.class)
class ReferentialAdapterTest {

    @Mock
    private JPAQueryFactory queryFactory;
    // Mock QueryDSL的更新查询对象
    @Mock
    private JPAUpdateQuery<QServiceConfigEntity> updateQuery;

    @InjectMocks
    private ReferentialAdapter referentialAdapter;
  
    @Test
    void shouldEnableServicesConfig() {
        String roleCode = "CA_ICS_HBE";
        String countryIsoCode= "FR";
        List<String> services = Arrays.asList("VT" , "CAF");
        
        // 配置mock调用链
        when(queryFactory.update(any(QServiceConfigEntity.class))).thenReturn(updateQuery);
        when(updateQuery.where(any(BooleanExpression.class))).thenReturn(updateQuery);
        when(updateQuery.set(any(QBooleanPath.class), anyBoolean())).thenReturn(updateQuery);
        when(updateQuery.execute()).thenReturn(1L); // 返回更新条数,可自定义

        referentialAdapter.enableServiceConfigs(roleCode,countryIsoCode,services);
        
        verify(queryFactory,times(1)).update(any(QServiceConfigEntity.class));
        verify(updateQuery, times(1)).where(any(BooleanExpression.class));
        verify(updateQuery, times(1)).set(eq(QServiceConfigEntity.serviceConfigEntity.isEnabled()), eq(Boolean.TRUE));
        verify(updateQuery, times(1)).execute();
    }
}
额外提示

原业务代码中存在一处疏漏:serviceIds变量未定义,你需要补充从services列表转换为对应服务ID的逻辑(比如通过查询QServiceEntity获取ID),否则业务代码本身运行时也会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:55:24