1

Thanks in advance for any help.

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:

  • Add a delete all function to the cache class
  • Use a class extension and implement the functionality there - it would mean a fair amount of copy paste
  • Change private functions / variables to be internal giving enough access to easily create a delete all function in a class extension
  • Stop worrying because only protocols are used by classes consuming the service so it doesn't matter if functions and properties within the class are not private

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.