Strategy-Pattern:当并非所有方法都抛出异常时,抑制 JUnit 中特定测试的异常警告
Strategy-Pattern: Surppress warning of exception for specific test in JUnit when not all method throw an exception
说明代码:
public Interface FlightBehaviour {
void fly();
}
public class Fly implements FlightBehaviour {
@Override
public void fly() throws CrashWithObject {
// does something to fly
}
}
public class CanNotFly implements FlightBehaviour {
@Override
public void fly() {
// does not fly
}
}
public class Bird() {
private FlightBehaviour fly;
public void setFlightBehaviour(FlightBehaviour flightBehaviour) {
this.car = car;
}
@Override
public void fly() throws CrashWithObject {
car.fly();
}
}
JUnit:
@Test
public void testFlighBehaviourOfNonFlyingBird() {
// ...
Bird plasticDuck = new Bird();
plasticDuck.setFlightBehaviour(new CanNotFly());
plasticDuck.fly(); //Compiler shows that an Exception is thrown
// However, I know that this will never happen since my Bird can't fly
// and therefore never throws an exception
// ...
}
这是我的实施的简单复制。如您所见,我正在使用策略模式。
我的问题是:如何抑制给出的警告?
在测试用例中,您不应该假设不会抛出异常,而是测试它(通过在出现异常时使测试失败,也许在试图激怒它之后)。
使用您的(基于策略模式的)代码结构,编译器几乎不可能推断出不会抛出任何异常。我们作为人类已经面临着这种推理的艰巨工作(忽略代码中的一些拼写错误):
Bird.fly()
方法仅在 fly.fly()
抛出 CrashWithObject
时抛出。
fly
最近被设置为 plasticDuck.setFlightBehaviour(new CanNotFly());
中的 CannotFly
。
CannotFly.fly()
不会抛出 CrashWithObject
.
- 可能
setFlightBehaviour()
没有在其他任何地方为这个 Bird
实例调用,但这需要对整个应用程序进行全面分析才能真正确定这一点。
- 所以我们期望
fly
字段在 plasticDuck.fly()
调用时仍保留 CannotFly
的实例,这使我们可以得出结论,没有 CrashWithObject
可以扔。
你看,它需要对各种代码片段进行大量不平凡的推理才能得出无例外的结论,我不希望很快在编译器中看到这种推理的深度。
说明代码:
public Interface FlightBehaviour {
void fly();
}
public class Fly implements FlightBehaviour {
@Override
public void fly() throws CrashWithObject {
// does something to fly
}
}
public class CanNotFly implements FlightBehaviour {
@Override
public void fly() {
// does not fly
}
}
public class Bird() {
private FlightBehaviour fly;
public void setFlightBehaviour(FlightBehaviour flightBehaviour) {
this.car = car;
}
@Override
public void fly() throws CrashWithObject {
car.fly();
}
}
JUnit:
@Test
public void testFlighBehaviourOfNonFlyingBird() {
// ...
Bird plasticDuck = new Bird();
plasticDuck.setFlightBehaviour(new CanNotFly());
plasticDuck.fly(); //Compiler shows that an Exception is thrown
// However, I know that this will never happen since my Bird can't fly
// and therefore never throws an exception
// ...
}
这是我的实施的简单复制。如您所见,我正在使用策略模式。
我的问题是:如何抑制给出的警告?
在测试用例中,您不应该假设不会抛出异常,而是测试它(通过在出现异常时使测试失败,也许在试图激怒它之后)。
使用您的(基于策略模式的)代码结构,编译器几乎不可能推断出不会抛出任何异常。我们作为人类已经面临着这种推理的艰巨工作(忽略代码中的一些拼写错误):
Bird.fly()
方法仅在fly.fly()
抛出CrashWithObject
时抛出。fly
最近被设置为plasticDuck.setFlightBehaviour(new CanNotFly());
中的CannotFly
。CannotFly.fly()
不会抛出CrashWithObject
.- 可能
setFlightBehaviour()
没有在其他任何地方为这个Bird
实例调用,但这需要对整个应用程序进行全面分析才能真正确定这一点。 - 所以我们期望
fly
字段在plasticDuck.fly()
调用时仍保留CannotFly
的实例,这使我们可以得出结论,没有CrashWithObject
可以扔。
你看,它需要对各种代码片段进行大量不平凡的推理才能得出无例外的结论,我不希望很快在编译器中看到这种推理的深度。