Getting NullPointerException While trying to implement EqualsVerifier

40 views
Skip to first unread message

Haroen Viaene

unread,
Nov 15, 2016, 4:00:23 AM11/15/16
to equalsverifier
Hey,

First of all, thanks for your project, it's a great idea and looks like it will make my life easier.

However I had a bit of trouble implementing it. 

As you can see in this PR https://github.com/gin-fizz/pollistics/pull/11, the tests still fail 

EqualsVerifier.forClass(User.class)
  .withPrefabValues(Poll.class, new Poll(), new Poll())
  .usingGetClass()
  .verify();


When not covering it in a try/catch block I get 

com.pollistics.models.UserTest > equalsContract FAILED
    java.lang.NullPointerException
        at com.pollistics.models.Poll.equals(Poll.java:74)
        at nl.jqno.equalsverifier.EqualsVerifier.withPrefabValues(EqualsVerifier.java:198)
        at com.pollistics.models.UserTest.equalsContract(UserTest.java:30)

The equals check looks pretty normal I think, except that the classes use each other. 

@Override
public boolean equals(Object obj) {
  if(this == obj)
    return true;
  if((obj == null) || (obj.getClass() != this.getClass()))
    return false;

  User user = (User) obj;
  return this.getId().equals(user.getId());
}

Thanks for your answer 😊

Haroen Viaene

unread,
Nov 15, 2016, 5:23:43 AM11/15/16
to equalsverifier
I'm now noticing that the problem is at my own, because I didn't initialise the id

Jan Ouwens

unread,
Nov 18, 2016, 2:33:55 AM11/18/16
to equalsverifier
Hi Haroen,

Sorry I wasn't able to reply sooner.

You're right, the issue is that the id is undefined. Unfortunately, setting it in the constructor won't help, because EqualsVerifier bypasses it.

There are two ways you can make the EqualsVerifier test pass. Either you can add a null check in the equals method:
    return this.getId() == null ? user.getId() == null : this.getId().equals(user.getId());
(Or simply use Objects.equals(this.getId(), user.getId()) )

Or, you can add a line to your call to EqualsVerifier:
    EqualsVerifier.forClass(User.class)
      .withPrefabValues(Poll.class, new Poll(), new Poll())
      .usingGetClass()
      .suppress(Warning.NULL_FIELDS)
      .verify();

The first approach is correct if id is allowed to be null (because if something can be null, you have to check for it). The second approach is correct if id is never allowed to be null.


Good luck!
Jan


--
You received this message because you are subscribed to the Google Groups "equalsverifier" group.
To unsubscribe from this group and stop receiving emails from it, send an email to equalsverifie...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages