Unit testing memory leaks

Viewed 12148

I have an application in which a lot of memory leaks are present. For example if a open a view and close it 10 times my memory consumption rises becauses the views are not completely cleaned up. These are my memory leaks. From a testdriven perspective i would like to write a test proving my leaks and (after I fixed the leak) asserting I fixed it. That way my code won't be broken later on. So in short:

Is there a way to assert that my code is not leaking memory from a unit test?

e.g. Can i do something like this:

objectsThatShouldNotBeThereCount = MemAssertion.GetObjects<MyView>().Count;
Assert.AreEqual(0, objectsThatShouldNotBeThereCount);

I am not interested in profiling. I use Ants profiler (which I like a lot) but would also like to write tests to make sure the 'leaks' don't come back

I am using C# / Nunit but am interesed in anyone having a philosophy on this...

6 Answers

How about something like:

long originalByteCount = GC.GetTotalMemory(true);
SomeOperationThatMayLeakMemory();
long finalByteCount = GC.GetTotalMemory(true);
Assert.AreEqual(originalByteCount, finalByteCount);
Related