在沪务工的Polk、互拍👏👏👏
[技术]Mockito-使用
开发这么久真没好好Unit Test过,今天使用了以下Mockito,感觉挺强大,我的业务都是线程处理的,mock也都能实现。
1、引入spring的test依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
2、对feign进行mock
@MockBean AccountRemoteFeign mockFeign; @Test public void testA01Fail() throws InterruptedException { //当执行mockFeign.recording方法时,返回的内容 //注意mockFeign.recording不能是void Mockito.when(mockFeign.recording(Mockito.any())).thenReturn(ResultResponse.wrap(ResultEnum.NOENOUGHMONEY)); //业务代码, 只要后面用到AccountRemoteFeign,都已经被mockito处理了 }
3、对feign进行timeout异常mock
Mockito.when(mockFeign.recording(Mockito.any())).thenThrow(RetryableException.class);
4、对mapper进行mock
对service直接mock会导致mapper不生效,原理未研究...
@MockBean TbRecepSettleQueueMapper mockSettleQueueMapper; @Test public void testG03Fail() throws InterruptedException { Mockito.when(mockSettleQueueMapper.insert(Mockito.any())).thenThrow(RuntimeException.class); }
5、对同一个方法mock多次返回不同的值
Mockito.when(mockFeign.recording(Mockito.any())).thenReturn(ResultResponse.wrap(ResultEnum.SUCCESS), null, ResultResponse.wrap(ResultEnum.SUCCESS));
6、对void方法mock异常-未尝试
//insert有返回值可以这样使用 Mockito.when(mockSettleQueueMapper.insert(Mockito.any())).thenThrow(RuntimeException.class); //insert没有返回值需要这样使用,但我未测试 Mockito.doThrow(RuntimeException.class).when(mockSettleQueueMapper).insert(Mockito.any());
7、一个具体test例子
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = SettlementApplication.class) @ActiveProfiles("local") public class OperTest { @MockBean AccountRemoteFeign mockFeign; @Autowired private BatchSettleServiceImpl batchSettleServiceImpl; @MockBean TbRecepSettleQueueMapper mockSettleQueueMapper; /** * 1、A01成功 * 2、G04失败,创建A01回滚,A01回滚失败 * 3、oper pending */ @Test public void tesA01RevertFail() throws InterruptedException { //A01第一次成功,第二次pending Mockito.when(mockFeign.recording(Mockito.any())).thenReturn(ResultResponse.wrap(ResultEnum.SUCCESS), ResultResponse.wrap(ResultEnum.NOENOUGHMONEY)); //G03失败 Mockito.when(mockSettleQueueMapper.insert(Mockito.any())).thenThrow(RuntimeException.class); //请求参数 AddSettleQueueRequest request = this.initRequest(); //执行, 只会返回受理成功 BaseResponse response = batchSettleService.receiveSettle(request); Assert.assertEquals(true, response.getIsSucc()); //轮询结果 QuerySettleQueueRequest queryRequest = this.initQueryRequest(request.getItemId()); int i = 0; QuerySettleQueueResponse queryResponse = null; while(i < 5) { queryResponse = batchSettleService.querySettleQueueResult(queryRequest); Assert.assertEquals( RecepRQueryResult.PROCESSING.val(), queryResponse.getVal()); Thread.sleep(1000); i++; } } }
喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。
发布评论…