Mockito静态方法嵌套调用模拟失败:断言列表大小不一致问题
问题解决
核心问题分析
- Mock链式调用存根失效:使用
RETURNS_DEEP_STUBS直接链式存根静态方法调用链时,Mockito无法正确绑定存根规则,导致methodCall2返回原类中的默认空列表。 - 断言方法使用错误:
Assert.equals仅返回布尔值,不会主动抛出断言错误,正确的断言逻辑应使用Assert.assertEquals。
修正后的测试代码
import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.util.ArrayList; public class YourTestClass { // 替换为你的测试类名 @Test public void testMethod() { // 构建预期返回的列表,无需使用spy ArrayList<ArrayList<String>> expectedList = new ArrayList<>(); for(int i = 0; i < 2; i++) { expectedList.add(new ArrayList<>()); } expectedList.get(0).add("A"); expectedList.get(0).add("B"); expectedList.get(1).add("C"); expectedList.get(1).add("D"); // 手动mock ClassA实例,存根methodCall2的返回值 ClassA mockClassA = Mockito.mock(ClassA.class); Mockito.when(mockClassA.methodCall2(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(expectedList); // Mock静态类StaticClass,指定methodCall1返回mock的ClassA实例 try(MockedStatic<StaticClass> mockedStatic = Mockito.mockStatic(StaticClass.class)) { mockedStatic.when(() -> StaticClass.methodCall1(Mockito.anyString())) .thenReturn(mockClassA); // 调用目标方法获取结果 ArrayList<ArrayList<String>> actualList = StaticClass.methodCall1("anyString") .methodCall2("String1","String2","String3"); // 使用正确的断言方法验证结果 Assert.assertEquals(expectedList, actualList); } } }
关键调整说明
- 移除不必要的Spy:直接创建普通ArrayList作为预期返回值即可,无需监视对象行为。
- 分步Mock链式调用:先mock中间对象
ClassA并存根其方法,再mock静态方法返回该mock对象,确保存根规则正确生效。 - 修正断言方法:使用
Assert.assertEquals替代Assert.equals,确保结果不匹配时抛出AssertionError。
内容的提问来源于stack exchange,提问作者Usman Mohammed
相关产品推荐
相关产品推荐

