Mockito完成单元测试

1.引入maven依赖

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.23.4</version>
    <scope>test</scope>
</dependency>

Note: 此处的scope最好选择test。 因为test的scope是不可以继承的,即使其他模块引用了你所在的模块,没有什么影响。由于该依赖和powermock(Mock静态方法依赖)存在版本不兼容问题,如果其他模块依赖了该模块并继承了你的Mockito,UT运行会报错。

2.Mock 普通方法

     @InjectMocks
     private ABCService abcService = new ABCServiceImpl();

1. 校验boolean类型数据

ABC abc = new ABC();
abc.setId("id");
when(abcMapper.create(abc)).thenReturn(1);
Assert.assertTrue(abcService.create(abc));

2. 校验返回数据

ABC exceptedABC = new ABC();
ABC abc = new ABC();
when(abcMapper.selectABCById(abc)).thenReturn(abc);
ABC result = abcService.selectABCById(abc);
Assert.assertEquals(exceptedABC, result);

3. 校验抛出异常方法

Assertions.assertThatThrownBy(() -> abcService.getABCDetail("Id").isInstanceOf(abcException.class);

4.校验方法执行次数

Mockito.verify(abcService, Mockito.never()).abcGetUser(any(), anyList(), any()); //没有执行到
Mockito.verify(abcService).abcGetUser(any(), anyList(), any()); //默认执行一次
Mockito.verify(abcService, Mockito.times(n)).abcGetUser(any(), anyList(), any()); //执行n次

3.Mock 同一个类中方法之间调用

@InjectMocks
@Spy
private ABCService abcService = new ABCServiceImpl();
ABC abc = new ABC();
doReturn(abc).when(abcService).getCount(anyString()); //

4.Mock new的对象

添加两个注解到该测试类上

@RunWith(PowerMockRunner.class)
@PrepareForTest({UploadFileUtils.class, OkHttpClient.class})
 PowerMockito.whenNew(OkHttpClient.Builder.class).withNoArguments().thenReturn(builder);

5.Mock 静态方法

Mock静态方法需要引入如下依赖

    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito2</artifactId>
      <version>2.0.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <version>2.0.2</version>
      <scope>test</scope>
    </dependency>

这个依赖和上面的Mock依赖会有版本冲突的,慎用。 我现在一般就是让代码走到静态方法里面去。