最近,我试图验证我编写的对象是否使用单元测试正确释放。但是,我发现,无论我尝试了什么,在测试完成之前,该对象都不会释放。因此,我将测试简化为一个简单的示例(见下文),该示例试图证明使用弱变量进行对象去分配的基础知识。
在我看来,强引用应该在测试方法退出后停止保留对象,在下一个run循环中引用时弱引用应该是零。但是,弱引用永远不会为零,而且两个测试都失败了。我是不是误会了什么?下面是完整的单元测试。
class Mock { //class type, should behave with reference semantics
init() { }
}
class DeallocationTests: XCTestCase {
func testWeakVarDeallocation() {
let strongMock = Mock()
weak var weakMock: Mock? = strongMock
let expt = expectation(description: "deallocated")
DispatchQueue.main.async {
XCTAssertNil(weakMock) //This assertion fails
expt.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testCaptureListDeallocation() {
let strongMock = Mock()
let expt = expectation(description: "deallocated")
DispatchQueue.main.async { [weak weakMock = strongMock] in
XCTAssertNil(weakMock) //This assertion also fails
expt.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
}我认为XCTest可能在某种程度上推迟了取消分配,但是即使将测试方法体封装在autoreleasepool中也不会导致对象释放。
发布于 2016-12-23 22:46:07
问题是,当调用testWeakVarDeallocation()块时,您的dispatchAsync函数尚未退出,因此仍然保留对strongMock的强烈引用。
尝试这样做(允许testWeakVarDeallocation()退出),您将看到weakMock如预期的那样变为nil:
class weakTestTests: XCTestCase {
var strongMock: Mock? = Mock()
func testWeakVarDeallocation() {
weak var weakMock = strongMock
print("weakMock is \(weakMock)")
let expt = self.expectation(description: "deallocated")
strongMock = nil
print("weakMock is now \(weakMock)")
DispatchQueue.main.async {
XCTAssertNil(weakMock) // This assertion fails
print("fulfilling expectation")
expt.fulfill()
}
print("waiting for expectation")
self.waitForExpectations(timeout: 1.0, handler: nil)
print("expectation fulfilled")
}
}https://stackoverflow.com/questions/41308381
复制相似问题