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; } }