如何通过Mockito模拟父类方法?Mockito新手遇阻求助
解决Mockito模拟
getHttpReq().getSession()的问题 嗨,别着急,这个场景其实是Mockito中**部分模拟(Partial Mocking)**的典型应用,我来一步步帮你搞定:
核心思路
你的B类继承自A,prepare()方法依赖A的getHttpReq()返回的HttpServletRequest,再调用它的getSession()。我们需要:
- 模拟
HttpServletRequest和HttpSession这两个依赖对象 - 让
B的实例调用getHttpReq()时返回我们模拟的HttpServletRequest - 让模拟的
HttpServletRequest调用getSession()时返回模拟的HttpSession
完整测试代码示例
假设你用JUnit 5 + Mockito,代码如下:
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) public class BTest { // 模拟HttpServletRequest和HttpSession对象 @Mock private HttpServletRequest mockHttpReq; @Mock private HttpSession mockHttpSession; // 创建B的Spy实例:保留真实对象的行为,但可以替换特定方法的返回值 @Spy private B bInstance = new B(); @Test public void testPrepare() throws Exception { // 第一步:让B的getHttpReq()返回我们模拟的HttpServletRequest when(bInstance.getHttpReq()).thenReturn(mockHttpReq); // 第二步:让模拟的HttpServletRequest的getSession()返回模拟的HttpSession when(mockHttpReq.getSession()).thenReturn(mockHttpSession); // 调用要测试的prepare方法 bInstance.prepare(); // 验证行为:确认getHttpReq()和getSession()都被正确调用了 verify(bInstance, times(1)).getHttpReq(); verify(mockHttpReq, times(1)).getSession(); } }
关键细节解释
- 为什么用Spy而不是Mock?:因为我们需要
B的prepare()方法是真实执行的(只是依赖的部分方法需要模拟),Spy可以让我们保留对象的真实行为,只替换特定方法的返回值;如果用Mock的话,prepare()方法会默认什么都不做,不符合测试需求。 - 手动初始化版本(不用注解):如果你习惯手动管理对象,也可以这样写:
@Test public void testPrepareWithoutAnnotations() throws Exception { HttpServletRequest mockHttpReq = mock(HttpServletRequest.class); HttpSession mockHttpSession = mock(HttpSession.class); B bInstance = spy(new B()); when(bInstance.getHttpReq()).thenReturn(mockHttpReq); when(mockHttpReq.getSession()).thenReturn(mockHttpSession); bInstance.prepare(); verify(bInstance).getHttpReq(); verify(mockHttpReq).getSession(); } - 特殊情况处理:如果
A类的getHttpReq()是final方法,Mockito默认无法模拟,需要在src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker文件中添加一行mock-maker-inline来开启final方法的模拟支持。
内容的提问来源于stack exchange,提问作者Srividya
相关产品推荐
相关产品推荐

