简体   繁体   English

当使用assertEquals时,应该捕获哪种异常?

[英]What kind of exception should go in the catch with assertEquals?

I'm making a webdriver and part of it is to check the title to make sure that it is on the right page. 我正在制作一个网络驱动程序,其中一部分是检查标题以确保它在正确的页面上。 Just for my benefit now I want it to show a dialog box when it the title doesn't match but right now all it does is give me an error message in the console. 只是为了我现在的利益,我希望它在标题不匹配时显示一个对话框,但现在所做的只是在控制台中给我一条错误消息。 I believe it's my exception that is the problem. 我相信这是我的例外。 Any suggestions? 有什么建议么?

try{
    assertEquals("Current page title", "Account Inventory - Select Manager", pageTitle);
}
catch(Exception ex)
{

    JFrame frame = new JFrame("Message");
    JOptionPane.showMessageDialog(frame ,
            "The title does not match");
}

assertEquals with throw an AssertionError when the condition is not met. 当不满足条件时, assertEquals引发AssertionError So you should probably either catch that error explicitly, or widen your catch to include Throwable rather than Exception . 因此,您可能应该明确捕获该错误,或​​者扩大捕获范围以包括Throwable而不是Exception

See the type hierarchy diagram below to understand why catch (Exception e) won't catch an AssertionError . 请参阅下面的类型层次结构图,以了解为什么catch (Exception e)无法捕获AssertionError

java.lang.Object
  |--- java.lang.Throwable
         |--- java.lang.Error
                | --- java.lang.AssertionError  // not a descendent of Exception
         |--- java.lang.Exception

However... tests are generally supposed to be automated so I can't imagine why you'd want to introduce a human element by showing a dialog. 但是...测试通常应该是自动化的,因此我无法想象为什么您要通过显示对话框来引入人为因素。

Actually, assertions are not for handling exceptions, they are for asserting some test cases. 实际上,断言不是用于处理异常,而是用于断言某些测试用例。 If an asserted case doesn't come to be true, then there is a serious problem with the input causing the problem which require special attention, that's why you get AssertionError when an assertion fails. 如果断言的情况不成立,则输入存在严重问题,导致需要特别注意的问题,这就是为什么断言失败时会收到AssertionError的原因。

And I think you are mixing the intentions of using exceptions and errors. 而且我认为您正在混合使用异常和错误的意图。

I am assuming that this is unit test code. 我假设这是单元测试代码。 You can handle it in 2 ways. 您可以通过两种方式处理它。

  1. Catch the error and write error log. 捕获错误并写入错误日志。
  2. Do not catch the exception and to allow a method further up the call stack to handle it 不要捕获异常,并允许调用堆栈中的某个方法进一步处理该异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM