Reputation: 56
I have a caching service I've implemented with a core data stack in Swift 3.1. The exposed interface conforms to this protocol:
protocol WeekForecastCacheService {
func add(cacheModels: [DayForecastCacheModel])
func get(cityId: Int, callback: @escaping ([DayForecastCacheModel]?) -> () )
}
Ideally I want the internals of my core data stack to stay private.
However I also want to be able to unit test the class. Specifically the exposed interface. Because the core data stack is persistent I want to be able to delete every entity (a reset if you will to start tests in a known state). How do I go about doing this while keeping the unit test implementation outside of my main target.
Ideally I would also like my tests to be independent of implementation...
I'm thinking along the lines of the following but could do with some advice:
Upvotes: 1
Views: 344
Reputation: 70946
When unit testing Core Data, a typical approach is to use the in-memory store type to effectively remove the "persistent" part of Core Data. With an in-memory store you get all of Core Data's usual capabilities, but the persistent store isn't written to a file so it always starts off empty. That gets you to a known starting state. If necessary you can pre-load some other known state into the in-memory store before beginning the test.
The key for this is NSInMemoryStoreType
. If you're setting explicitly adding the persistent store, that would be the type
value when calling addPersistentStore(ofType:configurationName:at:options:)
. If you're using NSPersistentContainer
, you'd include the store type in the persistentStoreDescriptions
property.
Upvotes: 1