简体   繁体   中英

Is Eclipse's null check analysis confused by JUnit's 'fail'?

I have the following code:

Object foo = someMethod();
if (foo == null) 
    org.junit.Assert.fail("OMG what a horrible error!");
foo.doSomeStuff();

But Eclipse (Neon, M4.6) seems to be unable to detect that that org.junit.Assert.fail method will terminate execution flow, and complains that the last line contains a possible NPE, which it doesn't.

Is that a bug or am I using it wrong ?

Eclipse has a built in list of a few methods which it knows will not return. This includes the JUnit assertNotNull but does not include fail .

Eclise bug 382069 describes this support.

How is Eclipse supposed to know that? As far as it's concerned this is just another library call.

If you use it like this it should work without a NullPointerException:

Object foo = someMethod();
if (foo == null) {
   org.junit.Assert.fail("Jesus Christ what a horrible error!");
} else {
   foo.doSomeStuff();
}

Well, if Assert.fail() would not throw an exception, you would have an NPE. But why would Eclipse / Java know that.

Btw, it's better to use assertNotNull, so you won't have that problem anyway...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM