xUnit is great! If you haven’t used it yet it really is well worth the time to explore and get to grips with. I was recently creating some Serialization tests using the WCF DataContractSerializer. In order to make sure the test were all as I wanted/expected and to have a clean slate between each serialization test it is prudent to ensure the files generated by the tests are cleaned up afterwards. Here is a little class that provides exactly this through the use of a custom attribute. This also means that your test code isn’t polluted with unneccessary code clutter … neat!
Here is the class:
public class SerializationCleanupAttribute : BeforeAfterTestAttribute { public readonly string FileToCleanUp; public SerializationCleanupAttribute(string fileToCleanUp) { FileToCleanUp = fileToCleanUp; } public override void Before(System.Reflection.MethodInfo methodUnderTest) { if (File.Exists(FileToCleanUp)) { File.Delete(FileToCleanUp); } } public override void After(System.Reflection.MethodInfo methodUnderTest) { if (File.Exists(FileToCleanUp)) { File.Delete(FileToCleanUp); } } }
Here is a test using the class:
[Fact] [SerializationCleanup(FileName)] public void TestClientConfigSerialization() { ClientEndpointConfiguration config = new ClientEndpointConfiguration(); config.CloseTimeout = new TimeSpan(0, 10, 0); config.EndpointName = "Default"; config.EndpointNamespace = "http://jammer.biz/namespace/test/"; config.StoreToDisk(FileName); Assert.True(File.Exists(FileName)); }