[英]Creating a method in Java that will chain to other methods and call fail() if the previous method in the chain throws an exception?
Here's what I'm trying to accomplish.这就是我想要完成的。 I'm in a Java unit test using Mockito.
我正在使用 Mockito 进行 Java 单元测试。 I want to create a generic method for my project called
orFailIfExceptionThrown()
that I can chain to any method call in the test and basically just have it call fail("An unexpected exception was thrown", e)
inside the method.我想为我的项目创建一个名为
orFailIfExceptionThrown()
的通用方法,我可以链接到测试中的任何方法调用,基本上只是让它在方法内部调用fail("An unexpected exception was thrown", e)
。 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 学习的角度来看,我只是对如何完成它感兴趣。
Here's what you can't do, and a preferable alternative:这是你不能做的,也是一个更好的选择:
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 学习的角度来看,我只是对如何完成它感兴趣。
With this in mind, I'm not going to debate the merits of the alternative here - just know that the primary reason we don't do this, is because it can't be done.考虑到这一点,我不打算在这里讨论替代方案的优点 - 只知道我们不这样做的主要原因是因为它无法完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.