JUnit:我应该在assertNotNull之后执行null检查吗
我应该在JUnit:我应该在assertNotNull之后执行null检查吗,junit,Junit,我应该在assertNotNull之后进行空检查以避免测试代码中出现空指针吗?例如 assertNotNull(foo); if (foo != null) { assertNotNull(foo.getBar()); } 或者只是 assertNotNull(foo); assertNotNull(foo.getBar()); 你做得对 assertNotNull(foo); assertNotNull(foo.getBar()); 如果您以前做过,则无需设置其他条件来检查相同的
assertNotNull
之后进行空检查以避免测试代码中出现空指针吗?例如
assertNotNull(foo);
if (foo != null) {
assertNotNull(foo.getBar());
}
或者只是
assertNotNull(foo);
assertNotNull(foo.getBar());
你做得对
assertNotNull(foo);
assertNotNull(foo.getBar());
如果您以前做过,则无需设置其他条件来检查相同的情况。您对
assertNotNull(foo);
assertNotNull(foo.getBar());
如果以前做过,则不需要设置其他条件来检查相同的内容。甚至不需要进行第一次空检查。如果
foo
为空,测试将失败,出现NullPointerException
。是否进行空检查是一个品味问题。您甚至不需要进行第一次空检查。如果foo
为空,测试将失败,出现NullPointerException
。是否进行空检查是一个品味问题。使用assertX
方法确保实际断言条件。因此,通过使用assertNotNull
可以确保某些内容不为null
正确的方法如您所示:
assertNotNull(foo);
assertNotNull(foo.getBar());
如果您开始深入研究assertNotNull
方法,您将看到以下调用:
// First call
static public void assertNotNull(Object object) {
assertNotNull(null, object);
}
// Second call
static public void assertNotNull(String message, Object object) {
assertTrue(message, object != null);
}
// Third call
static public void assertTrue(String message, boolean condition) {
if (!condition) {
fail(message);
}
}
引用assertTrue文档:
断言某个条件为真。如果不是,则抛出带有给定消息的AssertionError
结论:在断言NOTNULL值后,您不必执行null检查,因为junit正在使用
assertX
方法为您处理这些问题,以确保条件确实被断言。因此,通过使用assertNotNull
可以确保某些内容不为null
正确的方法如您所示:
assertNotNull(foo);
assertNotNull(foo.getBar());
如果您开始深入研究assertNotNull
方法,您将看到以下调用:
// First call
static public void assertNotNull(Object object) {
assertNotNull(null, object);
}
// Second call
static public void assertNotNull(String message, Object object) {
assertTrue(message, object != null);
}
// Third call
static public void assertTrue(String message, boolean condition) {
if (!condition) {
fail(message);
}
}
引用assertTrue文档:
断言某个条件为真。如果不是,则抛出带有给定消息的AssertionError
结论,在断言NOTNULL值之后,您不必执行null检查,因为junit会为您处理这些问题