Java – Ways of creating expected object for assert

javatddtestingunit testing

Recently, I started to use TDD. It's really cool and fun but creating expected object for assertEquals is very boring and tedious.

At the moment I see only two way for that:

Straightforward
Creating object in code using million of setters. Using that approach greater part of tests is creating expected object. I think it's not very cool.

Serialization
Writing expected object for example in JSON and then serialize it in test. I can't find disadvantages of that way except possibility of inconsistent state between my beans and test files.

EDIT

toString() (@Kilian Foth comment)
Some kind of serialization, but I think it deserves attention. Define a strictly controlled toString() and then assert equality with a literal string rather than a second object.

Configuring in DI container(inspired by @Spotted)
I remembered about DI. Does anybody configure expected bean in DI (Spring XML for example) and then inject it to test method? Is it bad and unefficient approach or something normal?

Are there any other techniques/approaches or special tools that can accelerate that process?

Best Answer

Unless you are specifically testing the equals() method of a class, there is usually no reason for a unit test to assert the equality of two objects. A unit test should test one behaviour and not all features of a code unit, whether that is a module, a class or even a method (a method with many possible inputs usually needs many unit tests and not just one).

Therefore, there is often no need to create such a "comparison object". If you're verifying that a transaction puts your customer in the correct status, obtain the customer and assert things about its status, not that it's exactly equal to another complex object that the test provides. That is almost certainly testing too much an in a very brittle way, since any change to the customer class might break the "status" test.