Unit test for dealloc with ARC in iOS

I would like to write an iOS unit test for the dealloc method, which (basically) removes the object as a delegate to another object.

 - (void) dealloc { someObject.delegate = nil; } 

However, I cannot directly call dealloc when using ARC. What would be the best way to write this unit test?

+6
source share
3 answers

Assign an instance to a weak variable:

 MyType* __weak zzz = [[MyType alloc] init]; 

The instance will be deleted immediately.

Alternatively, you can disable ARC in your unit test file and call dealloc.

+5
source

The best 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 creates an instance of the class that we want to free inside @autorealase , which will be released (if we don't get lost) as soon as we exit the block. weakReference will contain a reference to the instance without saving it, which will be set to nil .

+4
source

In fact, you can use a custom startup pool to test dealloc-related behavior:

 - (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); } 
+2
source

Source: https://habr.com/ru/post/903007/


All Articles