iOSSnapshotTestCase快照测试失败:无法加载参考镜像问题求助
iOSSnapshotTestCase 参考图找不到问题排查方案
错误信息
/Users/xqc/Library/Mobile Documents/comappleCloudDocs/Xcode Projects & Resources/Snapshot/SnapshotTests/SettingsVCSnapshotTests.swift:26: error: -[SnapshotTests.SettingsVCSnapshotTests test_example] : failed - Snapshot comparison failed: Optional(Error Domain=FBSnapshotTestControllerErrorDomain Code=1 "Unable to load reference image." UserInfo={NSLocalizedFailureReason=Reference image not found. You need to run the test in record mode, NSLocalizedDescription=Unable to load reference image., FBReferenceImageFilePathKey=/Users/xqc/Library/Developer/CoreSimulator/Devices/A5B479B7-4DF1-B030-05CAF050B00C/data/Containers/Bundle/Application/629A7F7C-4264-B830/Snapshot.app/PlugIns/SnapshotTests.xctest/ReferenceImages_64/SnapshotTests.SettingsVCSnapshotTests/test_example@3x.png})
测试代码
import iOSSnapshotTestCase @testable import Snapshot final class SettingsVCSnapshotTests: FBSnapshotTestCase { private var sut: SettingsVC! override func setUp() { super.setUp() recordMode = false sut = SettingsVC() } override func tearDown() { sut = nil super.tearDown() } func test_example() { FBSnapshotVerifyViewController(sut) } }
排查步骤
修正录制模式的硬编码问题
代码中setUp里recordMode = false会直接覆盖Scheme环境变量的配置,导致录制模式不生效。要么注释掉这行,要么改成读取环境变量的逻辑:recordMode = ProcessInfo.processInfo.environment["FB_RECORD_SNAPSHOTS"] == "YES"同时确认Scheme的测试Target中,环境变量
FB_RECORD_SNAPSHOTS已设为YES(录制时)。检查参考图的生成与打包
- 运行录制模式后,到项目目录下找
ReferenceImages文件夹,确认是否生成了test_example@3x.png文件。 - 如果没有生成,手动在测试Target目录下创建
ReferenceImages文件夹,并将其添加到测试Target的Build Phases -> Copy Bundle Resources中,确保资源能被打包进测试包。
- 运行录制模式后,到项目目录下找
确保ViewController渲染完成
在执行快照前强制加载视图,避免因视图未初始化导致快照失败:func test_example() { sut.loadViewIfNeeded() FBSnapshotVerifyViewController(sut) }同时检查
SettingsVC的初始化是否完整,比如是否需要传入必要的配置数据,避免视图内容为空。清理缓存与重建项目
- 清空模拟器数据:打开模拟器,执行
Device -> Erase All Content and Settings。 - 清理Xcode构建缓存:执行
Product -> Clean Build Folder,之后重新构建并运行测试。
- 清空模拟器数据:打开模拟器,执行
验证测试Target配置
检查测试Target的Build Settings,确认Base SDK与当前使用的模拟器系统版本一致;同时确保Copy Bundle Resources中包含ReferenceImages文件夹或对应的图片文件。
内容的提问来源于stack exchange,提问作者Filippo
相关产品推荐
相关产品推荐

