[英]What to Assert or expect when checked exception occurs in Mockito Junit test
How to run a JUnit Test case on Checked Exception.如何在检查异常上运行 JUnit 测试用例。 For eg HttpClient execute method shows checked IOException but i am not sure what to assert/expect.例如,HttpClient 执行方法显示已检查的 IOException,但我不确定要断言/期望什么。
HttpClient httpClient = mock(HttpClient.class)
try {
when(httpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
//Ideally nothing should work after this as exception is thrown
//fail("This will fail") // this statement will throw Assertion Error
}
catch (IOException io) {
}
If i try using expected method, this returns IOException never thrown.如果我尝试使用预期的方法,这将返回从未抛出的 IOException。
Exception thrown =
assertThrows(
IOException.class,
() -> {
when(httpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
});
Truth.assertThat(thrown).hasMessageThat().contains("IOException");
}
If I correctly understood, You need annotation @Test.如果我理解正确,您需要注释@Test。 And you should assign field "expected" your exception class.并且您应该将字段“预期”分配给您的异常类。
@Test(excepted = IOException.class)
testMethod() {
throw new IOException();
}
In your test method you only stubbed httpClient.execute
method, but never called it.在您的测试方法中,您只存根了httpClient.execute
方法,但从未调用过它。 That is why no exception has been thrown.这就是为什么没有抛出异常的原因。
On top of that:最重要的是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.