如何让单元测试访问 Core Data 模型 [英] How to give unit tests access to Core Data models

查看:20
本文介绍了如何让单元测试访问 Core Data 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经在我的项目中制作了 Core Data 模型.我还有其他类的方法可以接受这些模型并根据它们的属性执行一些功能.我如何对这些类进行单元测试?

Let's say I've made Core Data models in my project. I have other classes with methods that take in these models and perform some function based on their properties. How do I unit test those classes?

对于普通的 Swift 文件,我在 Xcode 中选择它们并勾选一个框,使这些文件中定义的任何类对项目的单元测试部分可见.我的问题本质上是,如何让我的 Core Data 模型也对测试可见?

With normal Swift files I select them in Xcode and tick a box which makes any classes defined in those files visible to the unit test part of the project. My question is essentially, how do I make my Core Data models also visible to the tests?

请注意,我不想对 Core Data 堆栈执行任何操作,我只想能够创建模型的实例并将其传递给方法.

Note that I don't want to perform any operations on the Core Data stack, I just want to be able to create an instance of a model and pass it into a method.

推荐答案

由于 CoreData 使用托管对象,NSManagedObject 的任何子类在功能上毫无价值,除非附加到上下文.

Since CoreData uses Managed Objects, any subclass of NSManagedObject is functionally worthless unless attached to a context.

测试的一个技巧是在内存中创建一个 NSManagedObjectContext 并使用该上下文创建对象测试.此处概述

One trick for testing is to create an NSManagedObjectContext in memory and create objects test using that context. Outlined Here

这是在内存中创建上下文的代码:

Here's the code for creating the context in memory:

func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext {
    let managedObjectModel = NSManagedObjectModel.mergedModelFromBundles([NSBundle.mainBundle()])!

    let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)

    do {
        try persistentStoreCoordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil)
    } catch {
        print("Adding in-memory persistent store failed")
    }

    let managedObjectContext = NSManagedObjectContext()
    managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator

    return managedObjectContext
}

这篇关于如何让单元测试访问 Core Data 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆