为什么我不能在核心数据单元测试中强制转换 NSManagedObject?

问题描述 投票:0回答:1

我有一个名为“Lift”的简单实体和这个简单的单元测试:

func testLiftEntityCreation() {
    let lift = NSEntityDescription.insertNewObject(forEntityName: "Lift", into: managedObjectContext) as! Lift

    Logger.coreData.debug("The object is of type \(type(of: lift))")
    XCTAssertNotNil(lift)
    XCTAssertTrue(lift.isKind(of: Lift.self))
}

当我运行它时,我收到此错误:

Test Case '-[My_App_Tests.LiftTests testLiftEntityCreation]' started.
Could not cast value of type 'My_App.Lift' (0x6000029190b8) to 'My_App_Tests.Lift' (0x10f220df8).
2023-10-30 18:19:41.867620-0700 My_App[12267:1392673] Could not cast value of type 'My_App.Lift' (0x6000029190b8) to 'My_App_Tests.Lift' (0x10f220df8).

如果我删除强制转换,它会运行,但测试会失败,即使对象是 Lift 类型:

Test Case '-[My_App_Tests.LiftTests testLiftEntityCreation]' started.
2023-10-30 18:23:31.429225-0700 My_App[12291:1398106] [coredata] The object is of type Lift
../LiftTests.swift:20: error: -[My_App_Tests.LiftTests testLiftEntityCreation] : XCTAssertTrue failed

我已经阅读了我能找到的与此问题相关的三个 SO 问题,并确认数据模型检查器中的类名称为“Lift”,并且 Codegen 设置为类定义。

  1. 为什么选角失败?
  2. 当我删除强制转换时,为什么当我的调试语句确认它是“Lift”类型时它会失败?
swift unit-testing core-data
1个回答
0
投票

我发现我的 .xcdatamodeld 位于我的测试目标的编译源列表中。一旦我删除它,我就能够运行强制将对象强制转换为“Lift”的测试版本,并且它通过了。

© www.soinside.com 2019 - 2024. All rights reserved.