JPa/Hibernate/JUnit: How to use a proper method of reflection in the ToString?

405 views Asked by At

i would like to test my services in an architecture Spring/JPA/Hibernate via JUnit.

All is ok for moment, but i used an overriding method of ToString to verify the content :

@Override
public String toString() {
    return ToStringBuilder.reflectionToString(this, 
                    ToStringStyle.MULTI_LINE_STYLE);
}

It uses the library commons.lang. The result is correct, but when I check my entities that have relationships (Set for @ OneToMany or @ ManyToMany) it quickly becomes unreadable.

Anyone knows there a way to make JUnit test result more readable in the console?

Thank you.

1

There are 1 answers

1
Elias Dorneles On BEST ANSWER

I recommend using Lombok annotations @EqualsAndHashcode and @ToString.

@EqualsAndHashcode helps to avoid bugs and @ToString give you a nice readable output for toString().

You can exclude fields you don't want in them:

@EqualsAndHashCode(exclude={"someManyToManyCollection", "dontMather"})
@ToString(exclude={"someManyToManyCollection", "dontMather"})

or make them use only a field you are interested:

@EqualsAndHashCode(of={"id", "someKey"})
@ToString(of={"id", "someKey"})

This should allow you to get your readability with toString() and you can compare the objects with yourEntity.equals(otherEntity) in your tests.