过去,我通过在this post中描述的内存中设置托管对象上下文,在XCTests中测试了我的CoreData层。基本上是:
var item = (function () {
var items = {
helmet: {
byId: {
'Helmet of Smiting': {
id: 'Helmet of Smiting',
attack: 1000,
defense: 50
},
'Cheap Helmet': {
id: 'Cheap Helmet',
attack: 1,
defense: 2
},
'Steel Helmet': {
id: 'Steel Helmet',
attack: 50,
defense: 100
},
},
allIds: ['Helmet of Smiting', 'Cheap Helmet', 'Steel Helmet']
},
shield: {
byId: {
'Shield of Smiting': {
id: 'Shield of Smiting',
attack: 1000,
defense: 50
},
'Cheap Shield': {
id: 'Cheap Shield',
attack: 1,
defense: 2
},
'Steel Shield': {
id: 'Steel Shield',
attack: 50,
defense: 100
},
},
allIds: ['Shield of Smiting', 'Cheap Shield', 'Steel Shield']
}
};
function sortItems (type, attr) {
var itemType = items[type];
// duplicate the items
var sortedItems = itemType.allIds.slice();
sortedItems.sort(function (a, b) {
return itemType.byId[b][attr] - itemType.byId[a][attr];
});
return sortedItems;
}
var itemsConstructor = Object.create({
add: function (type, id, att, def) {
items[type].allIds.push(id);
items[type].byId[id] = {
id: id,
attack: att,
defense: def
}
},
get: function (type, id) {
if (typeof type === 'undefined') {
return items;
} else {
if (typeof id === 'undefined') {
return items[type];
} else {
return items[type].byId[id];
}
}
},
getStrongest: function (type, attr) {
return sortItems(type, attr)[0];
},
getStrongestSet: function (attr) {
var allItemTypes = Object.keys(items);
var strongestItems = {};
for (var i = 0; i < allItemTypes.length; ++i) {
var type = allItemTypes[i];
strongestItems[type] = sortItems(type, attr)[0];
}
return strongestItems;
}
});
return itemsConstructor;
})();
item.add('helmet', 'New Awesome Helmet', 999999, 999999);
console.log(item.getStrongestSet('defense'));
最近我一直在使用相同设置的Quick / Nimble,在class func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext {
let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])!
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
} catch {
print("Adding in-memory persistent store failed")
}
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
return managedObjectContext
}
语句中,它总是将我的NSManagedObject的属性读为nil,即使它在我调试测试时有值。例如,expect
是NSManagedObject实例,当我将其属性存储在变量中时,它将传递:
savedItem
但如果我直接测试let name = savedItem.name
it("should have a name") {
expect(name).to(equal(item.name))
}
:
savedItem.name
测试失败并显示消息:it("should have a name") {
expect(savedItem.name).to(equal(item.name))
}
如何使用Quick / Nimble直接测试我的CoreData对象?
答案 0 :(得分:0)
我遇到的奇怪行为似乎与我在NSManagedObject
闭包内但context
之前直接初始化it
这一事实有关。闭合。当我在beforeEach
闭包中(context
内部)初始化它时,它表现得如预期。