用powermock编写单元测试

1、pom文件引入jar包

XML 复制代码
<!-- 单元测试 start -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.0.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>2.0.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.github.jsonzou</groupId>
    <artifactId>jmockdata</artifactId>
    <version>4.1.2</version>
    <scope>test</scope>
</dependency>
<!-- 单元测试 end -->

2、创建单元测试用例目录

保持与main级别一致,并且具体的测试用例存放目录也跟源代码的目录级别保持一致

3、单元测试类的基本框架

java 复制代码
@RunWith(PowerMockRunner.class)
@PrepareForTest({CommonUtils.class}) // 工具类
public class OrderServiceTest {

    @InjectMocks
    private OrderService orderService;

    @Mock
    private OrderMapper orderMapper;
	
	@Mock
    private OrderHelper orderHelper;
	
	@Before
    public void setUp() throws Exception {
		PowerMockito.mockStatic(CommonUtils.class);
    }
	
	// 被测试的方法 orderService.pageOrderRecord有返回值
	@Test
    public void testPageOrderRecord() {
	
		// Gievn
        OrderRecordDTO orderRecordDTO = new OrderRecordDTO();
        orderRecordDTO.setId("111");
        orderRecordDTO.setPageIndex(1);
        orderRecordDTO.setPageSize(10);

		// When
        OrderRecordEntity orderRecord = JMockData.mock(OrderRecordEntity.class);
        List<OrderRecordEntity> mock = Lists.newArrayList();
        mock.add(orderRecord);
        PowerMockito.when(orderMapper.selectEntityListPage(any())).thenReturn(mock); // mock的方法有返回值
        PowerMockito.doNothing().when(orderHelper).fillData(any()); // mock的方法没有返回值
        PowerMockito.when(CommonUtils.doPageQuery(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(new PageRows<>()); // mock工具类方法

		// Run the test
        PageRows<OrderRecordDTO> rt = orderService.pageOrderRecord(OrderRecordDTO);
		
		// Verify the results
        Assert.assertNotNull(rt);
    }

}

4、常见单元测试问题

4.1、静态方法如何mock

参见基本框架里的CommonUtils.doPageQuery()的mock。

如果被测试类的方法中调用到了静态方法CommonUtils.doPageQuery(),在写测试类的时候就需要主要注意:

@PrepareForTest({CommonUtils.class})、

PowerMockito.mockStatic(CommonUtils.class);

4.2、返回类型为void的方法如何mock

参见基本框架里的orderHelper.fillData()方法的mock。

4.3、被@Value注解的值如何mock

ReflectionTestUtils.setField(对象,"成员变量","变量mock值");

被测试类:

java 复制代码
@Component
public class OrderExternalFacade {
    @Autowired
    private OrderAbility OrderAbility;

    @Autowired
    private OrderExternalConvertor OrderExternalConvertor;

    @Value("${switch.new.system:false}")
    protected boolean switchNewSystem;

	public PageRows<OrderVO> listOrder(OrderQueryVO OrderQueryVO) {
        if (switchNewSystem) {
            return OrderExternalConvertor.pageDto2PageVo(
                    OrderAbility.listOrder(OrderExternalConvertor.queryVo2ModelQuery(OrderQueryVO)));
        }
        return OrderExternalConvertor.pageDto2PageVo(
                    OrderAbility.listOrderFromEpm(OrderExternalConvertor.queryVo2QueryDto(OrderQueryVO)));
    }
}

单元测试类:

java 复制代码
@RunWith(PowerMockRunner.class)
public class OrderExternalFacadeTest {
    @InjectMocks
    private OrderExternalFacade OrderExternalFacade;

    @Mock
    private OrderAbility OrderAbility;

    @Mock
    private OrderExternalConvertor OrderExternalConvertor;

    @Test
    public void listOrder() {
        ReflectionTestUtils.setField(OrderExternalFacade, "switchNewSystem", true);
        when(OrderExternalConvertor.queryVo2ModelQuery(any())).thenReturn(new OrderModelQueryDTO());
        when(OrderAbility.listOrder(any())).thenReturn(new PageRows<>());
        when(OrderExternalConvertor.pageDto2PageVo(any())).thenReturn(new PageRows<>());
        PageRows<OrderVO> rt = OrderExternalFacade.listOrder(new OrderQueryVO());

        Assert.assertNotNull(rt);
    }
}

4.4、返回类型为void的方法如何断言

验证调用次数:verify(OrderService, times(1)).insertOrder(orderBO);

被测试类:

java 复制代码
public class OrderService{

	@Autowired
	private OrderDao OrderDao;
	

	/**
	 * 添加订单
	 * @param OrderBO
	 * @throws Exception
	 */
	@Override
	public void insertOrder(OrderBO OrderBO) throws Exception{
		OrderDao.insertOrder(OrderBO);
	}
}

单元测试类:

java 复制代码
@RunWith(PowerMockRunner.class)
public class OrderServiceTest {

    @InjectMocks
    private OrderService OrderService;

    @Mock
    private OrderDao OrderDao;

    @Before
    public void setUp() throws Exception {}


    @Test
    public void testinsertOrder() throws Exception {

        OrderBO orderBO = new OrderBO();
        orderBO.setHandleType("order");
        orderBO.setBoId("1234568");
        orderBO.setHandeleSuggest("submit");

        // 如何mock 返回类型为void的方法
        PowerMockito.doNothing().when(OrderDao).insertOrder(any());
      
        //when
        OrderService.insertOrder(orderBO);
        
        verify(OrderService, times(1)).insertOrder(orderBO);

    }

}

4.5、异常如何断言

被测试类:

java 复制代码
public void delete(List<String> ids, String requiredBillId) {
	RequiredBillEntity requiredBill = requiredBillMapper.selectEntity(requiredBillId);
	if (requiredBill == null){
		throw new BusinessException(RetCode.BUSINESSERROR_CODE, MessageConst.REQUIRED_BILL_NOT_FOUND);
	}

	if (!RequiredBillStatusEnum.DRAFT.getStatus().equals(requiredBill.getStatus())){
		throw new BusinessException(RetCode.BUSINESSERROR_CODE, MessageConst.REQUIRED_BILL_STATUS_NOT_DRAFT);
	}
	requiredBillDetailMapper.deleteEntities(new ParamsMap("id_IN", ids));
}

测试类:

java 复制代码
@Test
public void testDelete() {

	List<String> ids = Lists.newArrayList();
	ids.add("dddd");
	String requiredBillId = "ddd";

	when(requiredBillMapper.selectEntity(anyString())).thenReturn(null);

    // 断言业务异常
	try {
		requiredBillDetailService.delete(ids,requiredBillId);
		fail("Expected BusiException");
	} catch (BusiException e) {
		assertEquals(RetCode.BUSINESSERROR_CODE, e.getExCode());
		assertEquals(REQUIRED_BILL_NOT_FOUND, e.getMessage());
	}

}

简洁的一点的话:

java 复制代码
@Test
public void testDelete() {

	List<String> ids = Lists.newArrayList();
	ids.add("dddd");
	String requiredBillId = "ddd";

	when(requiredBillMapper.selectEntity(anyString())).thenReturn(null);

    // 断言业务异常
	Assert.assertThrows(BusinessException.class, () ->requiredBillDetailService.delete(requiredBillDetailDTO));

}
相关推荐
王解7 小时前
Jest项目实战(4):将工具库顺利迁移到GitHub的完整指南
单元测试·github
Devil枫18 小时前
Vue 3 单元测试与E2E测试
前端·vue.js·单元测试
小袁在上班1 天前
Python 单元测试中的 Mocking 与 Stubbing:提高测试效率的关键技术
python·单元测试·log4j
测试19981 天前
外包干了2年,快要废了。。。
自动化测试·软件测试·python·面试·职场和发展·单元测试·压力测试
安冬的码畜日常1 天前
【The Art of Unit Testing 3_自学笔记06】3.4 + 3.5 单元测试核心技能之:函数式注入与模块化注入的解决方案简介
笔记·学习·单元测试·jest
王解1 天前
Jest项目实战(2): 项目开发与测试
前端·javascript·react.js·arcgis·typescript·单元测试
程序员小雷2 天前
软件测试基础:单元测试与集成测试
python·功能测试·selenium·测试工具·单元测试·集成测试·压力测试
王解2 天前
Jest进阶知识:深入测试 React Hooks-确保自定义逻辑的可靠性
前端·javascript·react.js·typescript·单元测试·前端框架
程序员雷叔2 天前
外包功能测试就干了4周,技术退步太明显了。。。。。
功能测试·测试工具·面试·职场和发展·单元测试·测试用例·postman
安冬的码畜日常2 天前
【玩转 Postman 接口测试与开发2_005】第六章:Postman 测试脚本的创建(上)
javascript·测试工具·单元测试·postman·bdd·chai