【问题标题】:Creating a method in Java that will chain to other methods and call fail() if the previous method in the chain throws an exception?在 Java 中创建一个方法,该方法将链接到其他方法并在链中的前一个方法抛出异常时调用 fail()?
【发布时间】:2020-01-22 16:36:37
【问题描述】:

这就是我想要完成的。我正在使用 Mockito 进行 Java 单元测试。我想为我的项目创建一个名为orFailIfExceptionThrown() 的通用方法,我可以将它链接到测试中的任何方法调用,并且基本上只是让它在方法内部调用fail("An unexpected exception was thrown", e)。我对我是否应该这样做并不thaaaat 感兴趣,因为我可以看到为什么我应该或不应该这样做的两面。从纯 Java 学习的角度来看,我只是对如何完成它感兴趣。

【问题讨论】:

    标签: java generics chaining


    【解决方案1】:

    这是你不能做的,也是一个更好的选择:

    method().failOnExcept();     // BAD: as soon as method() terminates unexpectedly
                                 // failOnExcept() cannot be called - instead, control flow
                                 // shifts to a catch block (error handling) or the caller
                                 // of the method (if error handling failed/re-throws)
    failOnExcept(() -> method()) // GOOD: we attempt to try method(); if it fails,
                                 // failOnExcept() will handle it somehow
    

    我对我是否应该这样做并不感兴趣,因为我可以看到为什么我应该或不应该这样做的两面性。从纯 Java 学习的角度来看,我只是对如何完成它感兴趣。

    考虑到这一点,我不会在这里讨论替代方案的优点 - 只知道我们不这样做的主要原因是因为它无法完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多