I'm writing tests for a component that takes very complex objects as input. These tests are mixes of tests against already existing components, and test-first tests for new features.

Instead of re-creating my input objects (this would be a large chunk of code) or reading one from our data store, I had the thought to serialize a live instance of one of these objects, and just deserialize it into test setup.

I can't decide if this is a reasonable idea that will save effort in long run, or whether it's the worst idea that I've ever had, causing those that will maintain this code will hunt me down as soon as they read it.

Is deserialization of inputs a valid means of test setup in some cases?

To give a sense of scale of what I'm dealing with, the size of serialization output for one of these input objects is 93KB. Obtained by, in C#:

2 Answers
2

The biggest issue you will face with this scheme is that of versioning - if any of the types in your serialized graph changes (property added/removed/renamed for instance), serialization is likely to fail as will all the tests that rely on the object graph that was serialized.

For that reason alone I would avoid serialization. Use a builder method instead.

Creating objects manually tests the code involved in creating the object. Traditionally, this area of the code is very poorly exercised in tests, especially if compared to the code of your business logic. Going the serialization route is definitely possible, but you should keep in mind that you may need to add more tests to verify the object creation code through the regular non-serialization API.

If you do decide to use serialized instances, try making the format human-readable (XML? JSON?), perhaps at the cost of producing a larger file. This will let you deal with small insignificant version changes better than with the binary-serialized objects.