0

I've got a Hibernate class that I do not implement an equals method on.

My service layer has many methods which return this class.

For example, one of my service layer methods is:

public List<User> getUsers() {
    return this.userRepository.findAll();
}

where User is simply

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "email", nullable = false)
    private String email;
}

In my test code, I would like to assert equality between the objects the service methods return and the objects I expect them to return.

However, it makes no sense to implement an equals method on the Hibernate class which checks that all fields are equal (as discussed in The JPA hashCode() / equals() dilemma).

At the moment to solve this I'm converting my Hibernate class into a class which does have an equals method which checks each field is equal. It works, but it's not too elegant.

Is there a better way to do this?

jd96
  • 535
  • 3
  • 12
  • Do you have any business key in your entity classes? – code_mechanic Apr 04 '21 at 06:26
  • Yeh but I want to assert that all fields are equal, not just that the business keys are equal. I'll post up my class so the question is more clear. – jd96 Apr 04 '21 at 08:34
  • 1
    Which assertion library? Usually, assertion libraries provide means to compare objects field by field, or using a custom comparator. In AssertJ, you would use `isEqualToComparingFieldByFieldRecursively()`, for instance – crizzis Apr 04 '21 at 08:40
  • Ah interesting, using junit5 at the moment. – jd96 Apr 04 '21 at 08:45

2 Answers2

0

Off the suggestion in the comments, this does pretty much what I'm looking for - https://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#custom-comparison-strategy

jd96
  • 535
  • 3
  • 12
0

If you're using assertj, you can use the built-in recursive comparison method to do a field-by-field comparison instead of using the equals method comparison. For example:

assertThat(result).usingRecursiveComparison().isEqualTo(expected);
Kevin
  • 1,080
  • 3
  • 15
  • 41