Mockito 3.3.0所有存根均被调用仍抛出UnnecessaryStubbingException的原因及解决
问题分析与解决
先还原你遇到的完整场景:
被测类代码
class Parent { Child getChild() { return null; } } class Child { List<String> getValues(String param) { return Collections.emptyList(); } }
JUnit测试代码
@Test public void name() { Parent parentMock = mock(Parent.class, RETURNS_DEEP_STUBS); when(parentMock.getChild().getValues("foo")).thenReturn(List.of("Something")); when(parentMock.getChild().getValues("bar")).thenReturn(List.of("Something")); assertThat(parentMock.getChild().getValues("foo")).hasSize(1); assertThat(parentMock.getChild().getValues("bar")).hasSize(1); }
抛出的异常信息
org.mockito.exceptions.misusing.UnnecessaryStubbingException: Unnecessary stubbings detected in test class: ClassTest
Clean & maintainable test code requires zero unnecessary code.
There are 1 unnecessary stubbings (click to navigate to relevant line of code):
- -> at ClassTest.name(ClassTest.java:59)
明明调用了两个存根却报错的原因
这完全不是你的代码问题——这是Mockito 3.3.0版本中针对深度存根(RETURNS_DEEP_STUBS)的一个已知Bug。在这个版本里,Mockito的严格存根检查逻辑在处理链式调用的存根时出现了判断错误,即便你在测试中明确触发了两个存根的调用,它还是误判其中一个存根未被使用。
解决方案
这个Bug在Mockito的后续版本中已经被修复:
- 有开发者反馈在3.4.3版本时该问题就已经不存在
- 升级至3.12.4版本也能彻底解决此问题
你只需要将Mockito的依赖版本升级到3.4.3及以上的稳定版本,这个异常就会消失,测试也能正常通过。
内容的提问来源于stack exchange,提问作者fluminis
相关产品推荐
相关产品推荐

