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.
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...
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?
Use _GTMDevLog :
See the Advanced Stuff | Unit Test Logging on this page.
More info on DevLogNAssert.
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?
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.
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.