Mockito when().thenReturn()始终返回null问题排查求助
解决Mockito when().thenReturn()配置失效返回null的问题
问题现象
执行shouldSetToZero_whenNull测试用例时,调试确认CoreService已生成Mock对象,但Mockito.when().thenReturn()的配置完全被忽略,调用coreService.get(user)始终返回null。尝试用eq(user)替换any(User.class)后问题依旧。
核心原因
重复初始化Mock对象:
测试类同时使用了@ExtendWith(MockitoExtension.class)和@BeforeEach中的MockitoAnnotations.openMocks(this)。前者已经会自动完成@Mock、@InjectMocks注解对象的初始化工作,后者会再次执行初始化流程,覆盖之前设置的when匹配规则,导致Mock调用返回默认的null值。
修复方案
删除@BeforeEach中的重复初始化代码,仅依靠MockitoExtension管理Mock对象的生命周期:
修正后的测试类代码:
@ExtendWith(MockitoExtension.class) public class LimitServiceTest { @Mock private CoreService coreService; @Mock private AuditService audit; @InjectMocks private LimitService service; @Test public void shouldReturnNull(){ assertThat(this.service.get(new User())).isNull(); } @Test public void shouldSetToZero_whenNull(){ User user = new User(); Mockito.when(this.coreService.get(any(User.class))) .thenReturn(new Limit()); assertThat(this.service.get(user)).extracting(Limit::getAvailable) .isEqualTo(0d); } }
额外排查点(若修复后仍有问题)
- 检查User类的equals/hashCode实现:如果后续需要使用
eq(user)进行精确匹配,需确保User类正确重写了equals()和hashCode()方法,否则Mockito无法识别对象匹配。 - 验证Mockito与JUnit版本兼容性:JUnit 5需要搭配Mockito 3.0及以上版本,版本不兼容可能导致注解失效。
内容的提问来源于stack exchange,提问作者smillis12
相关产品推荐
相关产品推荐

