Swift XCTest:验证弱变量的正确释放

时间:2016-12-23 22:13:22

标签: swift xctest weak capture-list

最近我试图验证我正确编写的对象使用单元测试来解除分配。然而我发现无论我尝试什么,在测试完成之前对象都不会解除分配。所以我将测试简化为一个简单的例子(见下文),试图用弱变量证明对象释放的基础知识。

在我看来,强引用应该在测试方法退出后停止保留对象,并且在下一个运行循环引用时,弱引用应该为nil。但是,弱引用永远不会为零,并且两个测试都会失败。我在这里误解了什么吗?以下是完整的单元测试。

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中也不会导致对象解除分配。

1 个答案:

答案 0 :(得分:4)

问题是,当调用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")
    }
}