Search code examples
javajunithamcrest

JUnit - Compare Value Objects


short question: I have the situation that I want to compare value objects in my JUnit tests. Those value objects only have a few fields of different types (but mostly primitive types). I create one object from an xml file and the other from a dataset from my database.

I solved it by overriding the equals method in my value object class and then compare those two by assertEquals(o1, o2). I want to know if there is another solution for this task. Maybe a solution with which I don't have to write equals methods for every value class (there are a few...)

I already experimented with Hamcrest, but not really successful. I tried assertThat(o2, is(equalTo(o1))); If the object is equal, the JUnit test is successful, but if not, the test is not failing but exits with an exception (don't think that's how it should work, right?)

I also thought of something with reflection to automatically compare all fields of the classes, but I don't know how to start.

Do you have a suggestion how something like this is solved the most elegant way?


Solution

  • You actually mentioned the 3 most popular techniques: 1. implement "good" equals method and use it from unit test as well. 2. use series of assertEquals() 3. Use assertThat()

    I personally used all these techniques found all of them pretty useful; the choice depends on concrete requirements. Sometimes I created comaprison utility class that contained series of assert methods for my value objects. This helps to re-use assertion code in different unit tests.

    According to my experience it is good idea to implement good equals(), hashCode() and toString() for all value objects. This is not too difficult. You can use EqualsBuilder, HashCodeBuilder and ToSringBuilder from Apache commons or utilities of Object introduced in java 7. This is up to you.

    If performance is not an issue (IMHO correct for 99.999% of real applications) use reflection based builders (from apache commons). This makes the implementations very simple and maintenance-less.

    In most cases using equals() in unit test is good enough. However if it is not good, use assertThat() or seriece of assertEquals() according to your choice.