使用属性expected 是一个非常弱的解决方案,因为您无法控制方法的哪条指令将引发异常。
即使我不明白加入他们的原因......这里有一些解决方案:
JUNIT4
@Test
public void xyzAndPqr(){
try {
abc.pqr(null);
fail("pqr does not throw NullPointerException");
} catch(NullPointerException npe) {};
try {
abc.xyz(null);
fail("xyz does not throw NullPointerException");
} catch(NullPointerException npe) {};
}
注意:catch 只接受 NullPointerException,因此如果方法抛出其他类型的异常,则测试正确失败
注意 1:在 catch 子句中,您可以检查其他条件(消息、原因等)
注意2:测试在第一个不正确的方法上失败,而不检查其余方法。要始终检查所有方法,您可以使用 Collector Rule 。
JUNIT5
import static org.junit.jupiter.api.Assertions.*;
@Test
public void xyzAndPqr(){
assertThrows(NullPointerException.class, () -> abc.pqr(null));
assertThrows(NullPointerException.class, () -> abc.xyz(null));
}
注意:如果您需要检查其他条件(消息、原因等),assertThrows 返回有效引发的 Throwable
注意1:测试在第一个不正确的方法上失败,而不检查其余方法。要始终检查所有方法,您可以使用 AssertAll 。
import static org.junit.jupiter.api.Assertions.*;
@Test
public void xyzAndPqr(){
AssertAll(
() -> assertThrows(NullPointerException.class, () -> abc.pqr(null)),
() -> assertThrows(NullPointerException.class, () -> abc.xyz(null))
);
}
带有 AssertJ 的 JUNIT(4 和 5)
(见http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#exception-assertion)
import static org.assertj.core.api.Assertions.*;
@Test
public void xyzAndPqr(){
assertThatNullPointerException().isThrownBy( () -> abc.pqr(null) );
assertThatNullPointerException().isThrownBy( () -> abc.xyz(null) );
}
注意:您可以在 assertJ 中使用流畅的语法:例如添加 .withMessage("...")
注意1:测试在第一个不正确的方法上失败,而不检查其余方法。要始终检查所有方法,您可以使用 AssertAll(如果在 JUnit5 中)或 assertJ 软断言(在这两种情况下)