简体   繁体   English

我应该如何处理自定义 Hamcrest 匹配器中的异常?

[英]How should I handle exceptions in custom Hamcrest matchers?

I am using JUnit and Hamcrest to do some automated testing.我正在使用 JUnit 和 Hamcrest 进行一些自动化测试。 To make my tests more readable I want to make a custom matcher however the code that I am calling in the matchesSafely method might throw exceptions.为了使我的测试更具可读性,我想创建一个自定义匹配器,但是我在matchesSafely 方法中调用的代码可能会引发异常。 I am unsure of how to handle such exceptions as the method signature for matchesSafely does not allow for throwing exceptions.我不确定如何处理此类异常,因为matchesSafely 的方法签名不允许抛出异常。

An example for illustration:举例说明:

public static Matcher<Session> hasObjectOfType(final Class<?> cls) {
    return new TypeSafeMatcher<Session>() {
        /* describeTo method skipped for brevity */
        protected boolean matchesSafely(Session session) {
            return session.provideList(cls.getName()).iterator().hasNext();
        }
    }
}

So what happens here is that session.provideList declares a checked exception and I need to handle that somehow.所以这里发生的是 session.provideList 声明了一个已检查的异常,我需要以某种方式处理它。 I see two possible ways of handling this but maybe I'm overlooking something:我看到了两种可能的处理方式,但也许我忽略了一些东西:

  1. Catch the checked exception and wrap it in a runtime exception which is then thrown.捕获已检查的异常并将其包装在运行时异常中,然后抛出该异常。
  2. Catch the checked exception and return false.捕获已检查的异常并返回 false。 In reality I'm using a TypeSafeDiagnosingMatcher so a concern here is that the mismatch description should then (probably?) be different for the two possible scenarios: an empty list or a thrown exception.实际上,我使用的是 TypeSafeDiagnosingMatcher,所以这里的一个问题是不匹配的描述应该(可能?)对于两种可能的场景是不同的:空列表或抛出的异常。

In any case which would be the best practice way of handling exceptions?在任何情况下,哪种是处理异常的最佳实践方式?

You want to be able to debug failing tests as quickly as possible.您希望能够尽快调试失败的测试。 Thus: you should prefer option 1.因此:您应该更喜欢选项 1。

Because in that case, your "enclosing" test will fail on that runtime exception;因为在这种情况下,您的“封闭”测试将因该运行时异常而失败; and it will print the exception content to you.它会向您打印异常内容。 So you know where and why your test failed.所以你知道你的测试失败的地方和原因。

Compare that to: silently turning the exception into "false";将其与:默默地将异常变成“假”; and ending up with assertThat telling you that your match failed.并以assertThat结束,告诉您您的匹配失败。 Maybe you could manage to give a meaningful message in the end;也许你最终可以设法传达一个有意义的信息; but still: you would have to put in some "energy" go get there.但仍然:你必须投入一些“能量”才能到达那里。 Option 1 comes for free - try/catch rethrow.选项 1 免费提供 - try/catch rethrow。

So, my advise: go for option 1 - and see how it works for you.所以,我的建议是:选择选项 1 - 看看它对你有什么作用。 If that is not "good enough" for some reason;如果由于某种原因这还不够“足够好”; then invest more time and see if option 2 somehow would improve things.然后投入更多时间,看看选项 2 是否会以某种方式改善情况。

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

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