我没有在 Xcode 中使用 IB,而是以编程方式构建了所有 UI。现在我想断言我的单元测试中的约束是正确的(是的,不在 UI 测试中)。
我有一些像这样的约束:
footer.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
footer.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
footer.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
footer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.08).isActive = true
现在我想在单元测试中对此进行测试。我可以断言页脚不为零,并且它具有除尺寸之外的预期属性,因为它们始终显示为 0。例如,这是我尝试过但没有用的方法:
XCTAssertTrue(subject.getFooterView().frame.origin.y == subject.view.frame.origin.y)
我认为应该是正确的,但它失败了。如果我打印每个属性的值,我可以看到值 subject.view.frame.origin.y 是 414 但值 subject.getFooterView( ).frame.origin.y 总是零。
对于我的页脚,所有其他属性(例如 frame.size.width 等)始终为 零。
谁能帮我理解一下?
最佳答案
这不能为您提供所需结果的原因在于 AutoLayout 的工作方式。在调用 View Controller 的 viewDidLayoutSubviews 方法之前,您将无法访问 frame.size.width 值,如果您正在测试,则可能在调用此方法之前运行此测试。
看这个答案here .
他提到尝试 setNeedsLayout 后跟 layoutIfNeeded?
关于swift - 测试以编程方式查看约束(在单元测试中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57394388/