說明
提供幾個簡單的例子即寒,說明如何利用Mockito + Powermock來做單元測試
一、POM 依賴
<mockito.version>1.10.19</mockito.version>
<powermock.version>1.7.0</powermock.version>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule-agent</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
這里mockito 使用1.x版本召噩,powermock使用1.7.0.
二母赵、Mockito+Powermock 實(shí)例
普通service方法
public class StoreServiceImpl implements StoreService {
private OrderDetailMapper detailMapper;
private OfflineOrderReasonService offlineOrderReasonService;
public int insertOrderDetail(OrderDetail orderDetail) {
int id = 0;
try {
id = detailMapper.insert(orderDetail);
} catch (Exception e) {
OfflineOrderReasonDO reasonDO = this.convertTo(orderDetail,2,"插入訂單信息異常");
offlineOrderReasonService.saveOfflineOrderReason(reasonDO);
LoggerUtil.error(logger, "[INSERT_ORDER_FAIL] msg=orderNo:"+orderDetail.getOrderNo(),"errorMsg:"+e.getMessage(),e);
}
return id;
}
}
單元測試
第一步 告訴junit使用PowerMockRunner執(zhí)行單元測試
@RunWith(PowerMockRunner.class)
public class StoreServiceImplTest{
第二步 利用注解mock對象
@InjectMocks
:添加了該注解的對象的方法是可以進(jìn)入,被執(zhí)行的
@Mock
:添加了該注解的對象所有的屬性和方法都是不可使用的
@InjectMocks
StoreServiceImpl storeService;
@Mock
private OrderDetailMapper detailMapper;
第三步 初始化mock對象
@Before
public void setUp() {
// 對定義了注解對象進(jìn)行初始化
MockitoAnnotations.initMocks(this);
prepareData();
}
第四步 編寫test方法
方法 | 說明 |
---|---|
方法 | 說明 |
PowerMockito.when(方法).thenReturn(預(yù)期返回值) | 模擬方法返回特定預(yù)期的返回值 |
PowerMockito.when(方法).thenThrow(異常) | 模擬方法執(zhí)行中拋出異常 |
@Test
public void insertOrderDetailTest() {
PowerMockito.when(detailMapper.insert(orderDetail)).thenReturn(1);
int id = storeService.insertOrderDetail(orderDetail);
// 驗(yàn)證是否進(jìn)入了detailMapper.insert
Mockito.verify(detailMapper).insert(orderDetail);
// 驗(yàn)證返回是否正確
Assert.assertEquals(1,id);
}
@Test
public void insertOrderDetailWithExceptionTest() {
// 執(zhí)行方法時(shí)拋異常
PowerMockito.when(detailMapper.insert(Mockito.any())).thenThrow(new NullPointerException());
// void的方法
PowerMockito.doNothing().when(offlineOrderReasonService).saveOfflineOrderReason(Mockito.any());
int id = storeService.insertOrderDetail(orderDetail);
Assert.assertEquals(0,id);
}