1、导入依赖包
<!-- 单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.8.47</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito2</artifactId> <version>1.7.1</version> <scope>test</scope> <exclusions> <exclusion> <artifactId>mockito-core</artifactId> <groupId>org.mockito</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.7.1</version> <scope>test</scope> <exclusions> <exclusion> <artifactId>objenesis</artifactId> <groupId>org.objenesis</groupId> </exclusion> <exclusion> <artifactId>mockito-core</artifactId> <groupId>org.mockito</groupId> </exclusion> </exclusions> </dependency> <!-- 单元测试-->
2、编写测试类
@PowerMockIgnore({ "javax.management.*" }) public class OrderServiceImplTest { /** * 注入测试对象类 */ @InjectMocks private OrderService orderService; /** * 注入需要mock的类(orderService类中存在调用myOrderService的方法) */ @Mock private MyOrderService myOrderService; /** * 初始化 */ @Before public void before() { orderService = new OrderServiceImpl(); myOrderService = PowerMockito.mock(MyOrderService.class); //第二个参数必须和OrderServiceImpl类中对MyOrderService类中的引用myOrderService一致 ReflectionTestUtils.setField(orderService,"myOrderService",myOrderService); } @Test public void testCreateOrder { //对所测试类中调用其他包中的方法进行mock,方法参数可随意化,但返回的对象必须要保证不发生空指针,即需要赋值的地方及时赋值。 ResultBean result = new ResultBean(); result.setCode("200"); Mockito.when(myOrderService.checkOnlyPrice(Mockito.any(OrderDO.class))).thenReturn(result); //此参数需实例化 MessageBO messageBO =orderService.createOrder("test"); //断言 Assert.assertEquals(messageBO.getCode(), "200"); } //异常测试 @Test public void testCreateOrderException { Mockito.when(myOrderService.checkOnlyPrice(Mockito.any(OrderDO.class))).thenThrow(new DataAccessException(""));//业务层catch的异常 try { accountDataService.getBFinAtAccountDataList(""); } catch (Exception e) { Assert.assertTrue(e instanceof BusinessException);//业务层throw的异常 } } }