4

I am working on a Java project where I have an ant build, which runs JUnit tests, which are monitored by Cobertura. That works great and we have kept our coverage very high. For some classes, like Hibernate entities, we have minimal code in them, but have equals and hashCode methods. Testing those is a huge pain, and drags down the coverage percentages. We've tried using EqualsVerifier two classes have references to each other, which occurs often in Hibernate entities.

We've considered using Commons EqualsBuilder, but then we lose the ability to have IDE's autogenerate the equals/hashCode methods. I know EqualsBuilder also can be done through reflection, but we don't want to lose runtime performance just for build-time unit test coverage.

An ideal situation would be if we could tell Cobertura to just ignore equals and hashCode methods, but the patches out there require us to annotate our classes, which seems a bit awkward.

So, I'm hoping for ideas from others as to what works well in such instances. Does anyone have any ideas for how to get this done?

Thanks!

Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
Jack Dreep
  • 125
  • 1
  • 5

2 Answers2

5

It seems to me like you need to make a decision: Either equals and hashCode are not important, and in that event you should just ignore the < 100% code coverage metric (or figure out how to ignore a method). Or they are important, and you should write the unit tests to exercise them. It may not be fun, but it sounds like you care if these methods work properly. In which case, you probably need to test them.

Nathan Feger
  • 19,122
  • 11
  • 62
  • 71
  • I do agree that all code should be tested. The mental struggle is with the manual coding of those tests. In this case, the equals method is auto-generated and it is correct. So, testing that is a test of the algorithm used. There is a very large number of branches involved, so the tests would be a series of combinations of setting things to some object or null to cover each side of each branch. Perhaps in the end the thing that would suit me best would be to submit a patch to EqualsVerifier to allow for classes that reference eachother. – Jack Dreep Oct 28 '11 at 17:57
  • They are 'right' at the moment they are created, but are they right after somebody adds another member variable to the object? That'd be the thing I'd worry about. – Nathan Feger Oct 28 '11 at 19:51
1

If it's not worth testing, it's probably not worth writing the code in the first place.

In other words: if your equals and hashcode methods are used anywhere in your production code, then you need code coverage. As simple as that. Else it will cause bugs. Trust me, it will.

And by the way, "testing those is a huge pain" should never be a reason enough to give up testing. Huge pain usually translates as big effort now, but worth it in the long run.

Guillaume
  • 22,694
  • 14
  • 56
  • 70