NSManagedObject subclass mocking
You can completely override the NSManagedObject
subclass property getters in a new stub subclass in your test target. self.init()
works fine.
class StubCar: Car {
convenience init(name: String = "") {
self.init()
self.stubbedName = name
}
var stubbedName: String = ""
override var name: String {
set {}
get {
return stubbedName
}
}
}
Now usage in a test is simply let stubCar = StubCar()
and there are no CoreData related crashes when production code accesses properties and you don't need to setup a full in memory CoreData stack at all. Override the setter as well if you need to. This assumes you have your data layer properly abstracted away so you can just inject these models where they're needed and write tests as such.
This is due to Car being an NSManagedObject subclass which means it has to be initialized with its designated initializer: initWithEntity:insertIntoManagedObjectContext:
.
In this small article you can find more info on working with NSMangedObjects and XCTests: https://www.andrewcbancroft.com/2015/01/13/unit-testing-model-layer-core-data-swift/