3

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#:

new BinaryFormatter().Serialize((Stream)fileStream, myObject);

1
  • Welcome to the lovely world of fixtures. They get out of date so easily, yet are so common...
    – Izkata
    Commented Sep 7, 2012 at 21:26

2 Answers 2

1

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.