我有一个使用Core Data作为其数据库的应用程序,我正在尝试为我的NSManagedObject
子类中编写的数据库查询编写测试用例,如果插入成功,它们将返回true。我正试图像这样在我的实体中插入一个对象:
func testDBInser() {
let appDelegate: AppDelegate = AppDelegate()
let managedObjectContext = appDelegate.persistentContainer.viewContext
let myObject: MyManagedObject = MyManagedObject(context: managedObjectContext)
myObject.id = 10
myObject.name = "testObj"
XCTAssertTrue(UserProfileModel().insertObjectToUserProfile(myObject))
}
但是我的测试得到了这个错误: NSManagedObject可能只在单个NSManagedObjectContext
中(或由其观察)答案 0 :(得分:0)
func testInsert {
// 1. Arrange
let dataStack: DataStack = {
let dataStack = DataStack(xcodeModelName: "ModelName")
do {
try dataStack.addStorageAndWait()
} catch let error {
XCTFail("Cannot set up database storage: \(error)")
}
return dataStack
}()
// 2. Action
do {
try dataStack.perform(synchronous: { transaction in
let object = transaction.create(Into<TestObject>())
object.name = "Test"
})
} catch let error {
XCTFail("Cannot perform database transaction: \(error)")
}
// 3. Assert
do {
try dataStack.perform(synchronous: { transaction in
guard transaction.fetchOne(From<TestObject>(), Where("name", isEqualTo: "Test")) != nil else {
XCTFail("Cannot get database object")
}
})
} catch let error {
XCTFail("Cannot perform database transaction: \(error)")
}
}