0

我正在尝试快照UITableViewController

我有一个简单的测试类

class FeedSnapshotTests: XCTestCase {
    
    // Fails
    func test_empty_feed_one() {
        let sut = UITableViewController(style: .grouped)
        sut.loadViewIfNeeded()
        record(snapshot: sut.snapshot(), named: "EMPTY_FEED_ONE")
    }
    
    // Passes
    func test_empty_feed_two() {
        let sut = UIViewController()
        sut.loadViewIfNeeded()
        record(snapshot: sut.snapshot(), named: "EMPTY_FEED_TWO")
    }
}

private extension FeedSnapshotTests {
    func record(snapshot: UIImage, named name: String, file: StaticString = #filePath, line: UInt = #line) {
        guard let imageData = snapshot.pngData() else {
            return XCTFail("Failed to generate PNG data representation from snapshot", file: file, line: line)
        }
        
        let snapshotURL = URL(fileURLWithPath: String(describing: file))
            .deletingLastPathComponent()
            .appendingPathComponent("snapshots")
            .appendingPathComponent("\(name).png")
        
        do {
            try FileManager.default.createDirectory(at: snapshotURL.deletingLastPathComponent(), withIntermediateDirectories: true)
            try imageData.write(to: snapshotURL)
        } catch {
            XCTFail("Failed to record snapshot with error: \(error)", file: file, line: line)
        }
    }
}

extension UIViewController {
    func snapshot() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: view.bounds)
        return renderer.image(actions: { action in
            view.layer.render(in: action.cgContext )
        })
    }
}

此时我只是试图创建一个UIImage并保存到磁盘。

然而,出于某种原因,在UITableViewController我无法对视图进行快照的情况下。如果我切换到UIViewController这个工作。

尝试创建我UImageUITableViewController测试时总是在这里失败

      guard let imageData = snapshot.pngData() else {
            return XCTFail("Failed to generate PNG data representation from snapshot", file: file, line: line)
        }
4

0 回答 0