Unit Testing Core Data

Ok, let me start by repeating one of my mantras: don’t unit test Apple’s code. We’re going to assume that Core Data works as designed. And we have pretty high confidence that this is the case because I have been told that the Core Data group actually unit tests their code.

What we need to unit test is the code that we write. I would also add to this that we should write tests for the Core Data boiler plate code. This is the code that is created by the Xcode project templates when we create a new project. I am fairly certain that Apple does not unit test their template code, judging by the times that unit tests fail to work upon a new release of Xcode. Since the boiler plate remains essentially the same for each project, it makes sense to create a reusable starting point project that includes unit tests and reuse that. I’ve created one of these for the Master-Detail Application and will be sharing it publicly once I decide how and where to put it. Even better would be a new set of project template files to do so, but at the rate that these change, I’m not sure I’m willing to sign up to do that đŸ™‚

In the boilerplate Master-Detail application code, the Core Data stack is instantiated in the appDelegate. So the tests for that code should appear in the appDelegate’s unit tests file. Once again, let me state that we don’t want to test that Core Data works as intended. We want to verify that our code works as intended.

Graham Lee, author of Test-Driven iOS Development, discusses using unit tests to perform what I would consider Core data integration testing. This is good information, and I won’t duplicate that here. Go buy the book. But since one of the premises of unit tests is that they execute quickly, we need to consider carefully whether or not to use the actual data model during unit tests, or to delegate that to integration tests. This of course will depend on how big the model is. A good approach might be to use the actual data model, and if unit tests begin to take too long, then revert to a test model.

I’ll stop here for this post, and add notes regarding specific Core Data components going forward. Please feel free to drop me a note regarding your experiences with unit testing Core Data. Many developers believe that Core Data code cannot be unit tested. I’m on a quest to dispel that notion.

 

Leave a Reply