powermock 基本使用
1、mock静态方法
例如要mock HttpUtils.post() 方法,该方法是静态方法
@RunWith(PowerMockRunner.class) @PrepareForTest({EsServiceImpl.class, HttpClientSignUtil.class}) public class EsServiceImplTest { @Test public void testSearch() { PowerMockito.mockStatic(HttpClientSignUtil.class); when(HttpClientSignUtil.post(any(),any(),any())).thenReturn("res")); } }
2、mock 局部变量
如
public class EmployeeService { public int getTotalEmployee() { EmployeeDao employeeDao = new EmployeeDao(); return employeeDao.getTotal(); } }
mock如下
@RunWith(PowerMockRunner.class) @PrepareForTest(EmployeeService.class) public class EmployeeServiceTest { @Test public void testGetTotalEmployeeWithMock() { EmployeeDao employeeDao = PowerMockito.mock(EmployeeDao.class); try { PowerMockito.whenNew(EmployeeDao.class).withNoArguments().thenReturn(employeeDao); PowerMockito.when(employeeDao.getTotal()).thenReturn(10); EmployeeService service = new EmployeeService(); Programming 系列丛书 int total = service.getTotalEmployee(); assertEquals(10, total); } catch (Exception e) { fail("测试失败."); } } }
3、mock apollo
@Value
public class RecruitPositionServiceImpl implements RecruitPositionService { @Value("${email.export.water.receiver:maoning02}") private String receiverOa; }
// ----------------------------------------------------------
@RunWith(PowerMockRunner.class) public class RecruitPositionServiceImplTest { @InjectMocks private RecruitPositionServiceImpl recruitPositionServiceImplUnderTest; @Before public void setUp() throws Exception { ReflectionTestUtils.setField(recruitPositionServiceImplUnderTest, "receiverOa", "receiverOa"); } }
@ConfigurationProperties
public class LongChatServiceImpl implements LongChatService { @Autowired PropertiesConfig propertiesConfig; } // -------------------------------------------------------------- @RunWith(PowerMockRunner.class) @PrepareForTest({LongChatServiceImpl.class, HttpClientSignUtil.class}) public class LongChatServiceImplTest { @Mock private PropertiesConfig mockPropertiesConfig; @InjectMocks private LongChatServiceImpl longChatServiceImplUnderTest; @Before public void setUp() throws Exception { longChatServiceImplUnderTest.propertiesConfig = mockPropertiesConfig; } }
标签:
单元测试
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)