You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftData单元测试加载模型数据时触发EXC_BREAKPOINT错误排查求助

SwiftData单元测试加载模型数据时触发EXC_BREAKPOINT错误排查求助

我最近在做SwiftData相关的单元测试时遇到了一个棘手的问题,折腾了好一阵都没解决,想请大家帮忙看看。

先说说我的场景:我写了一个makeModelContext方法在MainActor上创建内存版的ModelContext,用来避免和App的正式容器冲突,还禁用了自动保存防止测试时的后台持久化操作。代码大概是这样的:

/// Create an in-memory ModelContext containing all app models for testing.
/// This mirrors the models registered in the App's ModelContainer.
@MainActor static func makeModelContext() throws -> ModelContext {
    // Use an in-memory model configuration for tests to avoid CloudKit/SwiftData background
    // registration collisions with the app's shared ModelContainer.
    let config = ModelConfiguration(isStoredInMemoryOnly: true)
    let schema = Schema([
        Car.self,
        Charger.self,
        ChargingCostPlan.self,
        ChargingSession.self,
        ChargingSessionTemplate.self,
        PriceElement.self,
        Location.self,
        HomeConsumption.self
    ])
    let container = try ModelContainer(for: schema, configurations: [config])
    // Disable autosave to avoid background persistence during tests
    container.mainContext.autosaveEnabled = false

    return container.mainContext
}

然后在测试方法里,我同样在MainActor下调用这个方法获取上下文,接着加载测试JSON数据,准备导入:

@Test("Import a representative subset of the backup JSON")
@MainActor
func testImportRepresentativeSubset() async throws {
    // Locate the test data JSON next to this test file
    let testFileURL = URL(fileURLWithPath: #file).deletingLastPathComponent().appendingPathComponent("TestData_2026-03-07.json")
    let raw = try Data(contentsOf: testFileURL)

    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .iso8601
    let backup = try decoder.decode(DataEncoder.Backup.self, from: raw)

    let encoder = JSONEncoder()
    encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
    encoder.dateEncodingStrategy = .iso8601
    let data = try encoder.encode(backup)

    // Create an in-memory ModelContext (helper provided by test infra)
    let modelContext = try TestHelpers.makeModelContext()
    modelContext.autosaveEnabled = false

    // Import
    let report = try DataImporter.importFrom(data: data, into: modelContext)

    ...
}

导入方法importFrom也是标记在MainActor上的,结果在执行fetch现有Car对象的那一行,直接触发了Task 55: EXC_BREAKPOINT (code=1, subcode=0x1d9d2a8b4),测试直接停了:

@MainActor
public static func importFrom(data: Data, into modelContext: ModelContext) throws -> DataImportReport {
    var report = DataImportReport()

    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .iso8601

    do {
        let backup = try decoder.decode(DataEncoder.Backup.self, from: data)

        // Prefetch existing objects once to avoid repeated fetches and actor issues
        let existingCars: [Car] = (try? modelContext.fetch(FetchDescriptor<Car>())) ?? []
    ...
}

我已经排查了几个方向:

  • 所有需要的模型都已经注册到Schema里了
  • 打印过modelContext,看起来是有效实例
  • FetchDescriptor没有加复杂谓词,就是简单的全量查询,语法没问题

试过搜资料、问Copilot和Xcode助手,给出的方案都不管用。有没有大佬遇到过类似的问题?或者能指点下还有什么排查方向吗?

备注:内容来源于stack exchange,提问作者Ulrich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 18:35:30