Advertisement
codeuniv

EqualsVerifier library - test hashCode() / equals() correcteness

Feb 22nd, 2021
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. https://www.baeldung.com/java-equals-hashcode-contracts
  2.  
  3. EqualsVerifier library.
  4.  
  5. Let's add the EqualsVerifier Maven test dependency:
  6.  
  7. <dependency>
  8. <groupId>nl.jqno.equalsverifier</groupId>
  9. <artifactId>equalsverifier</artifactId>
  10. <version>3.0.3</version>
  11. <scope>test</scope>
  12. </dependency>
  13. Let's verify that our Team class follows the equals() and hashCode() contracts:
  14.  
  15. @Test
  16. public void equalsHashCodeContracts() {
  17. EqualsVerifier.forClass(Team.class).verify();
  18. }
  19. It's worth noting that EqualsVerifier tests both the equals() and hashCode() methods.
  20.  
  21. EqualsVerifier is much stricter than the Java SE contract. For example, it makes sure that our methods can't throw a NullPointerException. Also, it enforces that both methods, or the class itself, is final.
  22.  
  23. It's important to realize that the default configuration of EqualsVerifier allows only immutable fields. This is a stricter check than what the Java SE contract allows. This adheres to a recommendation of Domain-Driven Design to make value objects immutable.
  24.  
  25. If we find some of the built-in constraints unnecessary, we can add a suppress(Warning.SPECIFIC_WARNING) to our EqualsVerifier call.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement