如何解决如何为引发IOException并同时将ResourceRequest作为参数的方法编写JUnit
以下是将ResourceRequest作为参数的方法的代码
JSONObject updateDetail(ResourceRequest request) throws IOException {
BufferedReader resourceReqBr = new BufferedReader(
new InputStreamReader(request.getPortletInputStream()));
String resourceReqStr = resourceReqBr.readLine();
JSONObject updateCaDetailJsn = JSONObject.parse(resourceReqStr);
}
在这里,request.getPortletInputStream(),resourceReqBr.readLine()和JSONObject.parse(resourceReqStr)是引发IOException的代码行。如何设置请求对象,使其引发IOException。
我的测试代码:
@Mock
private ResourceRequest request;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testUpdatDetailIOException() throws Exception
{
expectedException.expect(IOException.class);
foo.updateDetail(request);
}
这导致空指针错误(很明显)。
解决方法
尝试在您的测试代码中进行以下模拟
// Code to satisfy SO!!!
// Not importart for this question
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
var seriesA = chart.series.push(new am4charts.LineSeries());
,
在我看来,仅对ResourceRequest的方法调用进行模拟以引发IOException并不是唯一的测试用例。
我还将尝试使JSONParser抛出IOException。例如,当json字符串有错误时,则期望IOException。
@Test
public void if_IOException_is_thrown_when_json_is_faulty() throws Exception {
expectedException.expect(IOException.class);
ResourceRequest mockResourceRequest = Mockito.mock(ResourceRequest.class);
Mockito.when(mockResourceRequest.getPortletInputStream()).thenReturn(
new ByteArrayInputStream("{[broken".getBytes(UTF_8)));
foo.updateDetail(mockResourceRequest);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。