Mockito+Powermock 单元测试简单使用说明
2019-01-07 本文已影响0人
masterFan
说明
提供几个简单的例子,说明如何利用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 实例
普通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执行单元测试
@RunWith(PowerMockRunner.class)
public class StoreServiceImplTest{
第二步 利用注解mock对象
@InjectMocks
:添加了该注解的对象的方法是可以进入,被执行的
@Mock
:添加了该注解的对象所有的属性和方法都是不可使用的
@InjectMocks
StoreServiceImpl storeService;
@Mock
private OrderDetailMapper detailMapper;
第三步 初始化mock对象
@Before
public void setUp() {
// 对定义了注解对象进行初始化
MockitoAnnotations.initMocks(this);
prepareData();
}
第四步 编写test方法
方法 | 说明 |
---|---|
方法 | 说明 |
PowerMockito.when(方法).thenReturn(预期返回值) | 模拟方法返回特定预期的返回值 |
PowerMockito.when(方法).thenThrow(异常) | 模拟方法执行中抛出异常 |
@Test
public void insertOrderDetailTest() {
PowerMockito.when(detailMapper.insert(orderDetail)).thenReturn(1);
int id = storeService.insertOrderDetail(orderDetail);
// 验证是否进入了detailMapper.insert
Mockito.verify(detailMapper).insert(orderDetail);
// 验证返回是否正确
Assert.assertEquals(1,id);
}
@Test
public void insertOrderDetailWithExceptionTest() {
// 执行方法时抛异常
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);
}