Div*_*hor 2 java rest junit mockito http-status-code-404
我有一个返回的第三方服务HttpClientErrorException.NotFound。当它返回此异常时,我从应用程序中抛出异常,表示输入无效,但对于所有其他异常(例如服务不可用等),我需要使用默认值并进一步继续。
我的代码块如下:
public String callService(String input)
{
String value = "";
try
{
value = service.callMethod(input);
}
catch(HttpClientErrorException.NotFound e1)
{
throw new ApplicationException("Invalid Input")
}
catch(Exception e)
{
value = "US";
}
return value;
}
Run Code Online (Sandbox Code Playgroud)
当我为此编写 JUnit 时,如何模拟 service.callMethod(input) 的调用并返回HttpClientErrorException.NotFound?
我尝试模拟并发送如下状态代码,但它不起作用。
Junit测试用例方法如下:
@Test(expected = ApplicationException.class)
public void callServiceInvalidInput() throws ApplicationException
{
String inputValue = "JLR";
when(externalService.callMethod(inputValue))
.thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));
String result = handler.callService(inputValue);
}
Run Code Online (Sandbox Code Playgroud)
当我模拟服务调用时,执行的 catch 子句是 Exception e 而不是前一个。原因是对象e在模拟时是instanceof HttpClientErrorException;但是当实际的服务调用发生时,它是 HttpClientErrorException$NotFound 的实例
当我尝试检查 NotFound 的实际设置方式时,我找到了答案。
when(externalService.callMethod(inputValue))
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "not found", null, null, null));
Run Code Online (Sandbox Code Playgroud)
我调用了 create 方法来返回该特定的内部类。
| 归档时间: |
|
| 查看次数: |
5906 次 |
| 最近记录: |