It is possible to use the memory assertions with a unit-testing framework, such as NUnit. Each memory assertion method returns a boolean value, which indicates whether the assertion succeeded or not. The return value can be used as argument to the unit test assertion:
Assert.IsTrue( MemAssertion.NoNewInstances( typeof( Control ), true );
It is also possible to add a handler to the MemAssertion.AssertionFailed event, which is raised when a memory assertion has failed. This is especially useful when using declarative assertions, since the assertion methods are not explicitly called. For example:
[TestFixture]
public class SomeMemoryTestFixture
{
[TestFixtureSetUp]
public void FixtureSetup()
{
MemAssertion.AssertionFailed += new EventHandler(
MemAssertion_AssertionFailed );
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
MemAssertion.AssertionFailed -= new EventHandler(
MemAssertion_AssertionFailed );
}
void MemAssertion_AssertionFailed(
object sender, EventArgs e )
{
// A memory assertion has failed. Inform the
// unit testing framework
Assert.Fail( “Memory assertion failed” );
}
[Test]
[NoNewInstances( typeof( Control ),
IncludeSubclasses=true )]
public void SomeTest()
{
// ...
}
}