assertEquals throws a NullPointerException, but equals method does not

I have two list objects and want to check that the first items of each are equal. However, I get a NullPointerException at this line:

assertEquals(instance.getPlane(0), planes.get(0));

This is the entire stack trace:

Testcase: testGetPlane(mypackage.PlaneTest): Caused an ERROR
null
java.lang.NullPointerException
at mypackage.PlaneTest.testGetPlane(PlaneTest.java:60)

(Line 60 is the assertion.)

Neither of those objects are null. I'm having a separate issue getting the debugger to work, so instead I added these printouts to my test case:

System.err.println("equals? " + instance.getPlane(0).equals(planes.get(0)));
System.err.println("equals? " + planes.get(0).equals(instance.getPlane(0)));

However, those lines executed without throwing any errors!

I've cleaned and built the project and restarted Netbeans, but still have this issue.

JUnit just calls expected.equals(actual) , which should be exactly the same thing as my printouts that aren't throwing the error, right? Why would assertEquals throw a NullPointerException, but equals on the same objects would not?


(I was about to post the question alone when I discovered the fix, but since it was a pain I'm posting it anyways in hopes this may help someone else. I did not find any other questions which had this solution.)

The error is in fact caused by JUnit, when it tries to compose an error message.

In the format function, there are the lines:

String expectedString = String.valueOf(expected);
String actualString = String.valueOf(actual);
if (expectedString.equals(actualString)) { ... }

String.valueOf(Object obj) returns obj.toString() if obj is not null.

My object's toString method simply returned a "name" field, which was never set inside the test. So, the object was not null, but the function returned null. This caused the NullPointerException when JUnit tried to call expectedString.equals . Ensuring that toString never returns null fixed the error.

链接地址: http://www.djcxy.com/p/76226.html

上一篇: 自动IllegalArgumentException消息?

下一篇: assertEquals抛出一个NullPointerException,但equals方法不会