You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 03:48:27