Skip to content

Instantly share code, notes, and snippets.

@danielbastidasr
Last active January 19, 2024 19:19
Show Gist options
  • Save danielbastidasr/a49faf6d07f8612dc19a830627ef1edc to your computer and use it in GitHub Desktop.
Save danielbastidasr/a49faf6d07f8612dc19a830627ef1edc to your computer and use it in GitHub Desktop.
Track memory leaks with XCTestCase
import XCTest
extension XCTestCase {
/// Given an instance, it will track at the end of every test case if it has been deallocated alerting about potential memory leak.
func trackForMemoryLeaks(_ instance: AnyObject, file: StaticString = #filePath, line: UInt = #line) {
addTeardownBlock { [weak instance] in
XCTAssertNil(instance, "Instance is not dealocated. Potential memory leak", file: file, line: line)
}
}
}
// MARK: - Usage
class MemoryLeakExampleTest: XCTestCase {
func test_BasicMemoryLeak() {
let systemUnderTest = AnInstanceOfAClass()
trackForMemoryLeaks(systemUnderTest)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment