Unit Testing in .NET Projects
Pages: 1, 2, 3, 4, 5
Next, a class factory wil be used to create an instance of the exception and
throw it. Again, the Assert.Ignore is used when the class factory has an error
(remember, we are testing the exception's ability to be serialized and
deserialized).
try
{
try
{
Stream = this.Serializer.SerializeToStream(ThrownException);
}
catch (SerializationException SerEx)
{
Assert.Fail(string.Format("Not able to serialize {0} {1}",
exceptionType.FullName, SerEx.Message));
}
catch (Exception OtherEx)
{
if (!(OtherEx.InnerException is SerializationException))
{
Assert.Fail(string.Format("Problem with {0} {1}",
exceptionType.FullName, OtherEx.ToString()));
}
else
{
Assert.Fail(string.Format("Not able to serialize {0} {1}",
exceptionType.FullName, OtherEx.ToString()));
}
}
Now that we have a thrown exception, let's get to the test. First we will try to
serialize it, and because we are going to want to deserialize it in just a
second, we will hold on to the stream. At that point, because we are actually
testing to see if there is a problem, we fail the test with Assert.Fail.
try
{
Clone = ((Exception)(this.Serializer.DeserializeToObject(Stream)));
}
catch (SerializationException SerEx)
{
Assert.Fail(string.Format("Not able to deserialize {0} {1}",
exceptionType.FullName, SerEx.Message));
}
catch (Exception OtherEx)
{
if (!(OtherEx.InnerException is SerializationException))
{
Assert.Fail(string.Format("Problem with {0} {1}",
exceptionType.FullName, OtherEx.ToString()));
}
else
{
Assert.Fail(string.Format("Not able to deserialize {0} {1}",
exceptionType.FullName, OtherEx.ToString()));
}
}
}
finally
{
if (Clone != null)
{
Assert.AreEqual(ThrownException.StackTrace, Clone.StackTrace);
}
if (Stream != null)
{
Stream.Close();
}
}
}
Now we will try and deserialize the stream back into the exception, creating a
clone. If this were not an example, I would need to be more thorough, but
here I have only verified the StackTrace. I want
to point out that the class used to test exception serialization is 170 lines, and
that 161 tests are generated from loading 18 assemblies. Now that is cool. By
the way, 24 exceptions failed; interestingly, 16 of them are from WSE. There are
many more cool, time-saving features in MbUnit. The last one I will mention is
the ability to take an existing NUnit test and simply change the reference and
using statement to MbUnit and voila, your conversion is done. MbUnit can be run
from the GUI application, from a console application, or from a NAnt task. It
has been integrated into Cruise Control .NET. And yes, you will see how it has been integrated into the VS.NET IDE.

Figure 2. MbUnit GUI application

