Re: UnitTest: object Should be Dealllocated
Re: UnitTest: object Should be Dealllocated
- Subject: Re: UnitTest: object Should be Dealllocated
- From: Jeffrey Robert Kelley <email@hidden>
- Date: Thu, 27 Jun 2013 21:58:09 -0400
I used Mike Ash’s excellent MAZeroingWeakRef before we had weak references. For unit tests, you could turn on all of its private API introspection, since it’s not shipping code.
Jeff Kelley
email@hidden | @SlaunchaMan | jeffkelley.org
On Jun 27, 2013, at 7:18 PM, Martin Wierschin <email@hidden> wrote:
>>> How can I create a Unit Test which tests such cases, e.g.:
>>>
>>> Foo* foo;
>>> @autoreleaspool {
>>> foo = [Foo new];
>>> [foo doSomething];
>>> foo = nil; // should deallocate foo
>>> }
>>> ASSERT_DEALLOCATED_TRUE(foo);
>>
>> Create a __weak reference to foo and assert that it is nil?
>
> That's the easiest, but if anyone needs to do this with older environments where you don't have zeroing weak references you can also accomplish this using ObjC's associated objects. Just create a special tracker object whose -dealloc method informs you of its deallocation, then set that tracker on foo using "objc_setAssociatedObject". When foo deallocates so will the tracker object.
>
> Basic idea:
>
> @implementation XXDeallocTracker
>
> + (void) trackDeallocForObject:(id)watchObj
> {
> XXDeallocTracker* tracker = [[XXDeallocTracker alloc] initTrackingObject:watchObj];
> [tracker release]; // watchObj now retains tracker by association, until watchObj deallocs
> }
>
> - (id) initTrackingObject:(id)obj
> {
> if( self = [super init] ) {
> objc_setAssociatedObject( obj, &key, self, RETAIN );
> }
> return self;
> }
>
> - (void) dealloc
> {
> // post NSNotification, call a block, or whatever you like to let the client know
> [super dealloc];
> }
>
> @end
>
>
>
> @implementation XXTextCase
>
> - (void) testEnsureDealloc
> {
> id foo = [foo newFoo];
> [XXDeallocTracker trackDeallocForObject:foo];
> [foo doSomething];
> [foo release];
> // make sure notification was received, block was called, or whatever strategy the tracker employed
> }
>
> @end
>
>
>
> That's typed into Mail and won't compile, but you get the idea.
>
> ~Martin
>
>
>
> _______________________________________________
>
> Cocoa-dev mailing list (email@hidden)
>
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>
> Help/Unsubscribe/Update your Subscription:
>
> This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden