Mockito单元测试报错:仅void方法可使用doNothing()问题排查
问题原因
报错的核心是Mockito的doNothing()仅支持无返回值(void)的方法,但你的ActRestClient.persistStoreStockKey()方法返回的是ResponseEntity<?>(有返回值),用doNothing()去mock这个方法就会触发异常。
解决方法
分两步调整测试代码:
- 保留对
PlanKeyService的doNothing():它的persistStoreStockKey()是void方法,用法合规。 - 替换对
ActRestClient的doNothing():用thenReturn()指定一个符合方法返回类型的有效值,比如模拟Feign调用成功返回的响应。
修改后的测试代码如下:
@Test void storeStockPersist() { Long idKey=1L; String name = "test"; Map params = Map.of("idKey",idKey,"name",name); StoreStockPersistRequest storeStockPersistRequest = new StoreStockPersistRequest(1L, "Test", params); // PlanKeyService是void方法,doNothing()用法正确 doNothing().when(planKeyService).persistStoreStockKey(storeStockPersistRequest); // 替换doNothing(),给有返回值的Feign客户端方法指定返回值 when(actRestClient.persistStoreStockKey(storeStockPersistRequest)) .thenReturn(ResponseEntity.noContent().build()); ResponseEntity<?> successfulCreate = planKeyController.storeStockPersist(storeStockPersistRequest); assertTrue(successfulCreate.getStatusCode() == HttpStatus.NO_CONTENT); }
补充说明
如果需要模拟Feign调用失败的场景,也可以用thenThrow()抛出异常,比如:
when(actRestClient.persistStoreStockKey(storeStockPersistRequest)) .thenThrow(new FeignException.BadRequest("模拟请求失败", null, null, null));
内容的提问来源于stack exchange,提问作者gcpdev
相关产品推荐
相关产品推荐

