Unit test for dealloc with ARC in iOS
Assign an instance to a weak variable:
MyType* __weak zzz = [[MyType alloc] init];
The instance will be dealloced right away.
Alternatively, you can disable ARC on your unit test file and call dealloc.
A better solution is simply
- (void)testDealloc
{
__weak CLASS *weakReference;
@autoreleasepool {
CLASS *reference = [[CLASS alloc] init]; // or similar instance creator.
weakReference = reference;
// Test your magic here.
[...]
}
// At this point the everything is working fine, the weak reference must be nil.
XCTAssertNil(weakReference);
}
This works creating an instance to the class we want to deallocate inside @autorealase
, that will be released (if we are not leaking) as soon as we exit the block. weakReference
will hold the reference to the instance without retaining it, that will be set to nil
.
You can actually use a custom autorelease-pool to test dealloc-related behaviour:
- (void) testDealloc {
id referencedObject = ...
@autoreleasepool {
id referencingObject = [ReferencingObject with:referencedObject];
...
}
// dealloc has been called on referencingObject here, unless you have a memory leak
XCTAssertNil(referencedObject.delegate);
}