Unit Testing [Serializable]

May 20, 2010 — Keith Dahlby

A common struggle with unit testing is figuring when to just assume somebody else’s code works. One such example is serializability: for simple classes, it should “just work” so we shouldn’t need to write a unit test for each of them. However, I still wanted to be able to verify that all classes in certain namespaces were marked as [Serializable], so I wrote the following test:

After we have a reference to the Assembly under test, we use a LINQ to Objects query against its types. If a type matches our namespace filter, we make sure it’s serializable if it should be. Finally, by using ToArray() and ShouldBeEmpty() we’re given a nice error message if the test fails:

Other than IsExempt(), the code should be more or less self-explanatory. If you had never bothered to check how static classes are represented in IL, now you know: abstract (can’t be instantiated) + sealed (can’t be inherited). Also, note that !IsPublic will cover compiler-generated classes for iterators and closures that we don’t need to serialize.

The final piece is providing a way we can exempt certain classes from being tested:

Of course, this isn’t a replacement for actually testing that custom serialization works correctly for more complicated objects, particularly if your classes may depend on others that aren’t covered by these tests. But I have still found this test to be a useful first level of protection.

Well it’s a design rule, but it’s also a functional requirement. And we’re not doing static analysis, so this works until we find do. :) Could you point me to an example of how this same kind of verification would be done with static analysis?