How do I use mock MOC in my viewcontroller with Xcode 7 UITests?

时间:2015-10-29 15:41:44

标签: swift core-data xctest moc uitest

So I have found that when writing XCTests or UI tests, I can't access my app delegate's MOC. I got some kind of error that said "I am MyAppUITests and I cannot access MyApp stuff."

Cool, no problem, I wrote all my code to accept any MOC and then made a mock MOC in setup() so that every XCTest has a fresh slate that doesn't touch my actual data. Import my app as testable. Boom, everything works, I don't have to change targets nor write any code in my objects to "force it work for testing!"

The problem is I am not sure how to do this for UI tests and with storyboards. Most of my view controllers get my MOC from appdelegate in viewdidload. I can't figure out how to tell it to use a mock moc so that every test can start clean and so that it doesn't use my actual core data store, but then also be able to work normally when not testing. The goal here is to have the main application code not have any references to it knowing that it is being tested.

There must be a clean way to do this without getting ugly, changing targets, etc. Something that will work like my XCTests did but for UI. I found this: How to start with empty Core Data for every UI Test Assertion in Swift?, but no one answered. This user is asking a similar question, but has the wrong approach I think (emptying core data instead of using a mock MOC).

Ideas?

For what it's worth, I'm building a Mac app.

1 个答案:

答案 0 :(得分:0)

  

问题是我不知道如何为UI测试和使用   故事板。我的大多数视图控制器都从appdelegate获取我的MOC   在viewdidload中。

您应该永远不要使用app委托来销售核心数据堆栈的众多原因之一。

没有详细说明你应该做什么,有一件事是清楚的:你应该为你的视图控制器提供一个MOC。

一种简单的方法(尽管也存在一些缺点)是为视图控制器提供MOC属性。

@property (strong) NSManagedObjectContext *managedObjectContext;

然后,您应该在初始化视图控制器时设置此属性。

一个快速但又脏的"让测试工作的方法是添加te属性,然后在viewDidLoad中执行类似的操作。

if (!self.managedObjectContext) {
    self.managedObjectContext = appDelegate.managedObjectContext;
}

这是这样做的建议。您应该完全摆脱应用程序委托中的核心数据堆栈,并且应该像将任何模型一样传递给视图控制器。

然而,它将允许您的应用程序继续像现在一样工作,并且还将为您提供一种在UI测试中实例化视图控制器并为其提供" mock" MOC。

此外,如果您不这样做,通常应该使用内存持久性存储来进行测试。