如何在JUnit中检查错误的Exception?

时间:2017-09-19 22:04:54

标签: java junit

我有这个方法:

public void updateService(JSONObject json, String url) throws IOException {
  PrintStream log = this.getLogger();
  CloseableHttpClient httpClient = null;

  httpClient = this.getCloseableHttpClient();
  log.println("Sending data to " + url);
  HttpPut request = new HttpPut(url);
  StringEntity params = new StringEntity(json.toString());
  request.addHeader("content-type", "application/json");
  request.setEntity(params);
  httpClient.execute(request);
  log.println("Sending report succeeded");
  httpClient.close();
}

我的测试然后执行此操作:

@Test
public void updateServiceCloseException() {
  RegistryTask task = new RegistryTask(false, null);
  RegistryTask spy = spy(task);
  CloseableHttpClient client = HttpClientBuilder.create().build();
  CloseableHttpClient clientSpy = spy(client);
  String url = "http://www.example.com/api/service/testo";
  String message = "Execute failure";

  JSONObject json = new JSONObject();
  json.put("name", "Bob");
  json.put("key", "testo");

  try {
    doReturn(clientSpy).when(spy).getCloseableHttpClient();

    // Make sure no http request is actually sent
    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    IOException exception = new IOException(message);

    doReturn(response).when(clientSpy).execute(any(HttpPut.class));
    doThrow(exception).when(clientSpy).close();

    spy.updateService(json, url);
  } catch (IOException e) {
    failWithTrace(e);
    // assertEquals(message, e.getMessage());
    return;
  } catch (Exception e) {
    failWithTrace(e);
    // assertEquals(message, e.getMessage());
    return;
  }

  fail("Exception not thrown");
}

出于某种原因,doThrow(exception).when(clientSpy).close();正在说Checked exception is invalid for this method!。但是考虑到我的方法有throws IOExceptionclose本身throws IOException,我对获取此JUnit异常感到困惑。

更新 我尝试将doReturn更新为when(clientSpy.execute(any(HttpPut.class))).thenReturn(response);。新例外是java.lang.AssertionError: java.lang.IllegalArgumentException: HTTP request may not be null。在这种情况下,不确定使用any的原因是null。这个问题实际上表明我应该使用doReturn,因为它始终有效thenReturn并非在所有情况下都有效... Mockito - difference between doReturn() and when()

1 个答案:

答案 0 :(得分:0)

我使用spymock更改为完整CloseableHttpClient clientSpy = mock(CloseableHttpClient.class);。我知道这会删除所有运行的方法,但我已经使用spy来覆盖我正在击中的两种方法。虽然这是解决方案,但我喜欢正确的解释作为未来读者的答案。