[英]Verify that exception was caught with Mockito and PowerMock
Is there any way to verify that exception was caught? 有没有办法验证异常是否被捕获? I mean that in my method there is a situation when I should catch the exception and in test I want to verify that exception was really caught. 我的意思是在我的方法中有一种情况,我应该捕获异常,在测试中,我想验证异常是否真正被捕获。
I think the answer is no -- perhaps you could pull it off with some intense reflection wrangling, but if so I don't think it would be worth your time. 我认为答案是否定的 - 或许你可以通过一些激烈的反思争论来解决这个问题,但如果是这样的话,我认为这不值得你花时间。
But I think (without seeing your method), you can probably still get full coverage on your method: 但我认为(没有看到你的方法),你仍然可以完全覆盖你的方法:
Hard to give any advice without any example. 没有任何例子,很难给出任何建议。 But if the exception wouldn't be caught it would went up till it reaches the test and the test would fail, because an exception was thrown. 但是如果异常没有被捕获,它会一直运行直到达到测试并且测试失败,因为抛出异常。 I know that doesn't verify that it was caught in a specific block but just that it was caught at all. 我知道这不会验证它是否被捕获在特定块中,而只是它被捕获了。
What does that exception do in your program if it is not caught? 如果没有捕获,那么您的程序中的异常会怎样? If it causes the program to crash, you can just run your Act part of the test within a try {} block. 如果它导致程序崩溃,您可以在try {}块中运行您的Act部分测试。 If it throws an exception you can catch it and fail the test. 如果它抛出异常,你可以捕获它并且不通过测试。
Another option, if the cacught exception causes a method to be called, say printToLog() you can verfiy that the method was indeed called with the correct parameters (using mockito). 另一种选择,如果cacught异常导致调用方法,比如printToLog(),你可以确认该方法确实是用正确的参数调用的(使用mockito)。
You should be able to mock the element that you want to throw the exception, so that it does throw the exception and then check that there were no calls to other methods that would be invoked if no exception had occurred. 您应该能够模拟要抛出异常的元素,以便它抛出异常,然后检查在没有发生异常的情况下没有调用其他方法。
Also check the state is as expected when an exception is thrown. 还会在抛出异常时检查状态是否符合预期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.