Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://www.baeldung.com/java-equals-hashcode-contracts
- EqualsVerifier library.
- Let's add the EqualsVerifier Maven test dependency:
- <dependency>
- <groupId>nl.jqno.equalsverifier</groupId>
- <artifactId>equalsverifier</artifactId>
- <version>3.0.3</version>
- <scope>test</scope>
- </dependency>
- Let's verify that our Team class follows the equals() and hashCode() contracts:
- @Test
- public void equalsHashCodeContracts() {
- EqualsVerifier.forClass(Team.class).verify();
- }
- It's worth noting that EqualsVerifier tests both the equals() and hashCode() methods.
- 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.
- 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.
- 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