In previous posts I described how I test serialization of objects.

However, I still forget to do this. So, I've written tests to remind me. This is an idea from Lean engineering called poka yoke (see http://en.wikipedia.org/wiki/Poka-yoke).

The concept is simple - make it impossible or hard for someone to make mistakes that go unnoticed.

I use the convention of putting all the classes that need to be serialized in a contracts namespace. This makes it simple to write a test to check all these classes are defined with the DataContract attribute.

        [Test]
        public void All_classes_in_contract_namespace_should_implement_datacontract()
        {
            IList allClassesInContractsNamespace = ReflectionHelper.GetAllTypesWhere(x=>x.Namespace.Contains("Contracts") && x.IsClass).ToList();

            allClassesInContractsNamespace.Count.ShouldBeGreaterThan(0);

            foreach (object obj in allClassesInContractsNamespace)
            {
                var dataContract = obj.GetType().GetCustomAttributes(typeof(DataContractAttribute), false).OfType().FirstOrDefault();
                dataContract.ShouldNotBe(null);
            }
        }

The ReflectionHelper extension method encapsulates how I'm using Autofac to get a list of types. This makes it simpler to re-use in my tests as well as change the method of reflecting over types in the future;

public static IEnumerable GetAllTypesWhere(Func predicate)
        {
            var builder = new ContainerBuilder();
            builder.RegisterAssemblyTypes(typeof(Invoice).Assembly)
                   .Where(predicate.Invoke)
                   .As();

            IContainer container = builder.Build();
            var controllers = container.Resolve<IEnumerable>();

            return controllers;
        }

This technique can be extended to any frequent mistake.

Conclusion

We have a lot of tools to help us not make mistakes; modern development tools help a lot. Third party tools exist such as re-sharper, style-cop, and FxCop. Our build systems run our unit tests and these static analysis tools.

We can take this further by writing tests that check for our most common mistakes.