作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这就是我想要实现的目标。我正在使用 Mockito 进行 Java 单元测试。我想为我的项目创建一个名为 orFailIfExceptionThrown()
的通用方法,我可以链接到测试中的任何方法调用,基本上只需让它调用 fail("抛出了意外的异常", e)
在方法内。我对我是否应该这样做不感兴趣,因为我可以看到为什么我应该或不应该这样做的两面。我只是对从纯 Java 学习的角度来看如何做到这一点感兴趣。
最佳答案
以下是您不能做的事情,以及更好的替代方案:
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
I'm not thaaaat interested in whether I should be doing this, as I can see both sides of why I should or should not do this. I'm just interested in how it could be done, from a pure Java learning standpoint.
考虑到这一点,我不会在这里争论替代方案的优点 - 只需知道我们不这样做的主要原因是因为它无法完成。
关于java - 在 Java 中创建一个方法,该方法将链接到其他方法,并在链中的前一个方法抛出异常时调用fail()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59864344/
我是一名优秀的程序员,十分优秀!