# Thursday, May 13, 2004

This is a bit convoluted, but stick with me...

We've got a fairly involved code generation process that builds C# classes from XSDs, which is all well and good.  The code generations uses some utility classes to help with reading the schema files, and those have unit tests, which is cool.  The code generation happens as part of our regular build, so if I screw up the CodeSmith tempate such that the code generation fails, I'll know about it at build time.  If I screw up the CodeSmith template such that the code generation succeeds, but the results don't compile, I'll also find out about that at build time. 

However, since the whole build/codegen process takes a while, it's not the kind of thing you want to run all the time after every change (as is the XP way).  So, how do I unit test the generated classes?  I think I have a workable solution, but it took some thinking about. 

I ended up writing a set of unit tests (using NUnit) that run the code generation process on a known schema.  The resulting C# file is then compiled using the CodeDom, then I can test the resulting class itself.  As a happy side benefit, I'll know if the CodeSmith template runs, and if the resulting C# compiles without having to run the whole build process.  Pretty cool.

An interesting side note: one of the things we do with our generated classes is serialize them as XML using the XmlSerializer.  I discovered during this process that if you generate an assembly with the CodeDom, you can't use the XmlSerializer on the resulting classes unless you write the assembly to disk.  I was using an in-memory only assembly, and the XmlSerializer gave me a very helpful exception stating that the assembly must be written to disk, which was easy enough to do.  I'm assuming that this is because the XmlSerialzer itself is going to generate another dymanic assembly, and it needs something to set it's reference to.  Interesting.

Comments are closed.