xcode 是否可以在测试运行期间检测自动版式约束问题?

siotufzp  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(106)

我希望我们的持续集成服务器在出现AutoLayout约束问题时失败。当约束问题发生时,是否可以搜索日志或在XCTestCase中检测?

btqmn9zl

btqmn9zl1#

你可以使用hasAmbiguousLayout视图属性来检测XCTest中不明确的布局。但是请注意,它可能不会返回与xcode控制台日志中相同的错误。下面是一个如何在视图控制器上检测该错误的示例。首先,将这些扩展添加到测试中:

extension UIView {
    func recursiveSubviews() -> [UIView] {
        return subviews + subviews.flatMap({ $0.recursiveSubviews() })
    }
}

extension XCTestCase {
    func checkViewControllerViewLoading(with viewController: UIViewController) {
        let window = UIWindow()
        window.rootViewController = viewController
        window.makeKeyAndVisible()
        XCTAssert(viewController.view != nil)
        viewController.view?.setNeedsLayout()
        viewController.view?.layoutIfNeeded()
        viewController.view?.recursiveSubviews().forEach { view in
            XCTAssert(view.hasAmbiguousLayout == false)
        }
    }
}

然后创建一个单元测试,如下所示:

func testMyViewControllerViewLoading() {
    checkViewControllerViewLoading(with: MyViewController())
}

如果你试图用下面的视图控制器运行这个测试,它将失败,除非你取消注解有宽度约束的行。

class MyViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let label1 = UILabel()
        label1.translatesAutoresizingMaskIntoConstraints = false
        let label2 = UILabel()
        label2.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(label1)
        view.addSubview(label2)
        NSLayoutConstraint.activate([
            label1.topAnchor.constraint(equalTo: view.topAnchor),
            label1.leftAnchor.constraint(equalTo: view.leftAnchor),
            label1.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            label2.topAnchor.constraint(equalTo: view.topAnchor),
            label2.leftAnchor.constraint(equalTo: label1.rightAnchor),
            label2.rightAnchor.constraint(equalTo: view.rightAnchor),
            label2.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            // uncomment this line to have a proper layout
            // label1.widthAnchor.constraint(equalToConstant: 50)
        ])
    }
}

相关问题