views:

399

answers:

6

What I am looking for is a way to programmatically verify a target object has been deallocated. Currently I have an NSLog statement in the dealloc methods of the objects I wish to observe. The unit testing framework is from the Google Toolbox for the mac, and it working nicely. I am just not certain how to frame this particular test.

A: 

Could you record the dealloc in some kind of event monitor service, so that the test code can then query with that to see if the dealloc has occured. Obviously you will record it by name or id, as the object is being dealloc'd...

Chris Kimpton
A: 

I may be naive, but wouldn't a unit test of a deallocation consist of

  • allocating an object,
  • deallocating it through your method to be tested,
  • trying to call something from the object, and then
  • catching the exception and see if its type is correct?
Svante
There's no exception to catch -- trying to dereference a pointer to memory that has been `free`d will crash.
Colin Barrett
+2  A: 

Use _GTMDevLog :

See the Advanced Stuff | Unit Test Logging on this page.

More info on DevLogNAssert.

Jeffrey Fredrick
Thanks, _GTMDevLog is exactly what I was looking for, now to figure out how to set it up within my unit test target.
Ryan Townshend
If this is exactly what you were looking for, and it helped you solve your problem, you should accept the answer ;)
Jason Coco
So thats what the check mark is for. I will do that, once I see it work.I still haven't successfully used this tip, and work has dragged me in a different direction for the time being.
Ryan Townshend
+1  A: 

I did something very similar to this in C#/.Net. I used a "WeakReference" to keep track of the item, and tested that it no longer existed (see link). Can you translate this approach to your environment?

http://geekswithblogs.net/HouseOfBilz/archive/2008/11/11/writing-tests-to-catch-memory-leaks-in-.net.aspx

Brian Genisio
+1  A: 

In the past I've created a variable that counts the number of objects of a given class that have been allocated by incrementing the value in the constructor and decrementing it in the destructor. The unit tests just check that the variable is zero at the end of the test.

David Norman
+1  A: 

You could swizzle the dealloc method. See MethodSwizzling on CocoaDev; a modern approach using Leopard's new method_exchangeImplementations function is (currently) near the bottom of the page.

Your implementation will need to tell your test case object that it had been called. One way to do this would be a static variable in the file where both the test case class and replacement dealloc method are defined; your test method sets that variable to NO, then releases the object, then asserts that the variable's value is now true.

Peter Hosey