用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));

}
相关推荐
hust_joker3 小时前
go单元测试和基准测试
开发语言·golang·单元测试
梦想画家2 天前
Golang Gin系列-8:单元测试与调试技术
golang·单元测试·gin
安的列斯凯奇2 天前
SpringBoot篇 单元测试 理论篇
spring boot·后端·单元测试
酱学编程4 天前
java中的单元测试的使用以及原理
java·单元测试·log4j
qw9495 天前
Spring 6 第6章——单元测试:Junit
spring·junit·单元测试
1234Wu5 天前
NodeJs如何做API接口单元测试? --【elpis全栈项目】
单元测试·node.js
逆风局?6 天前
JUnit单元测试
junit·单元测试
m0_672449608 天前
Java日志配置
java·开发语言·单元测试
大道之简8 天前
Mockito+PowerMock+Junit单元测试
junit·单元测试
程序员杰哥9 天前
Web自动化测试平台设计与落地
python·功能测试·selenium·测试工具·职场和发展·单元测试·测试用例