How do I write snapshot tests in UIKit with Swift?

Snapshot testing is a great way to ensure that your UIKit views render as expected over time. By taking a snapshot of the rendered view and comparing it to a reference image, you can catch unintended changes to your UI.

In this example, we will create a simple snapshot test in UIKit using Swift and the `snapshot` testing library. We will create a view controller and take a snapshot of its view.

import XCTest import UIKit import SnapshotTesting class MyViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let label = UILabel() label.text = "Hello, Snapshot Testing!" label.textAlignment = .center label.frame = view.bounds view.addSubview(label) } } class MyViewControllerSnapshotTests: XCTestCase { func testViewControllerSnapshot() { let viewController = MyViewController() viewController.view.frame = CGRect(x: 0, y: 0, width: 375, height: 667) assertSnapshot(matching: viewController, as: .image) } }

snapshot testing UIKit Swift unit tests image comparison UI testing