Saturday, June 18, 2016

Swift 3: Unit Testing Core Data With Generics

So I'm starting a new iOS app and using this opportunity to learn Swift. This app uses Core Data so I am going to be running unit tests to ensure that my data source class performs well. As anyone who has ever unit tested Core Data functionality knows, verifying the contents of the persistent store can get mind-bogglingly boiler-plate.

So instead you can leverage Swift's support for generics like so:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
func fetch<T: NSManagedObject>(entityType: T.Type, fromManagedObjectContext moc: NSManagedObjectContext) -> [T]
    {
        var results = [T]()
        let classNameComponents: [String] = entityType.description().components(separatedBy: ".")
        let className = classNameComponents[classNameComponents.count-1]
        
        let fetchRequest = NSFetchRequest<T>(entityName: className)
        do
        {
            results = try moc.fetch(fetchRequest)
        }
        catch
        {
            print("Error on GetSite: \(error)")
        }
        
        return results
    }


One thing to note is that generic methods typically take arguments that are instances of the types for which they are defined. But in this case we want to be able to simply use a class name in the parameter list because it's more clear that way. So the parameter entityType is actually of type T.Type. And the way we enter the argument for entityType is .self.

So hopefully this will make my Core Data unit testing less painful.

No comments:

Post a Comment