在XCTest中是否可以测试类属性是否属弱。
class A {
weak var p: String? = nil
}
结果:如果某个类的p属性较弱,则断言
答案 0 :(得分:1)
你可以使用这样的方法:
class TestObject {}
protocol A {
var a: TestObject? { get set }
}
class B: A {
var a: TestObject?
}
class C: A {
weak var a: TestObject?
}
func addVar(to: A) {
var target = to
target.a = TestObject() // Once we leave the scope of this function, the TestObject instance created here will be released unless retained by target
}
let b = B()
let c = C()
addVar(to: b)
addVar(to: c)
print(b.a) // prints Optional(TestObject) because class C uses a strong var for a
print(c.a) // prints nil because class B uses a weak var for a
转换为测试用例,它可能类似于:
func testNotWeak() {
func addVar(to: A) {
var target = to
target.a = TestObject() // Once we leave the scope of this function, the TestObject instance created here will be released unless retained by target
}
let testClass = B()
addVar(to: testClass)
XCTAssertNotNil(testClass.a)
}