【问题标题】:Test void function try/catch block with mockito [Spring-Boot] [duplicate]使用 mockito [Spring-Boot] [重复] 测试 void 函数 try/catch 块
【发布时间】:2021-10-06 01:57:29
【问题描述】:

我有以下情况。 我想使用 mockito 来测试我的服务功能的 try/catch 块:GettingMyDataService。请问有什么提示或技巧吗?

//in the controller
@GetMapping("/data")
public ResponseEntity gettingMyDataController(@RequestParam(request = true) String dataId) {

  gettingMyDataService.getDataFunction(dataId);
}
@Service
// my first service
public class GettingMyDataService {

  @AutoWired
   MyCustomRestClient myCustomRestClient

  
  public void getDataFunction(String dataId) {
    MyDataEntityDTO myDataEntityDTO; 
    
    try {
      myDataEntityDTO = myCustomRestClient.callReadExternalSIService(dataId);

    } catch (HttpStatusException e) {
      if (e.getStatusCode().value() == 404) {
        throw new CustomException1(".......");
      } 
      else {
        throw new CustomException2(".....");
      }
    }
}
@Service
// 2nd service for RestTemplate
public class myCustomRestClient {
  
  public callReadExternalSIService(String dataId) {
    String uri = "http:// ..."

    HttpEntity<MyDataEntityDTO> res = RestTemplate.getForEntity(uri + dataId, MyDataEntityDTO.class);
  
    return res.getBody(); 
  }
}

【问题讨论】:

  • 太棒了!谢谢你:)

标签: java spring-boot mockito try-catch resttemplate


【解决方案1】:

让您的自定义 REST 客户端抛出异常的示例:

MyCustomRestClient mock = Mockito.mock(MyCustomRestClient.class);
HttpStatusCodeException exception = new HttpClientErrorException(HttpStatus.NOT_FOUND);
Mockito.doThrow(exception).when(mock).callReadExternalSIService("data");

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 2017-02-25
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多