I'm writing a swift framework and I'm using a template from 'pod lib create' command. in my development pods, I've created a core data model file and I'm using core data in my framework. now I want to write unit tests for it. this is my unit test class code:
import XCTest
import CoreData
@testable import MyFramework
class MyClassTests: XCTestCase {
var testPersistentContainer: NSPersistentContainer?
override func setUp() {
let persistentStoreDescription = NSPersistentStoreDescription()
persistentStoreDescription.type = NSInMemoryStoreType
let container = NSPersistentContainer(name: "MyCoreDataModelFileName")
container.persistentStoreDescriptions = [persistentStoreDescription]
container.loadPersistentStores { (storeDescription, error) in
if let error = error {
fatalError(error.localizedDescription)
}
}
self.testPersistentContainer = container
}
override func tearDown() {
}
func testSomething() {
// the persistent container I'm trying to use is nil
XCTAssertNotNil(self.testPersistentContainer)
}
}
I know what is the problem, the problem is that the test target can't find my core data model file, and when I create a file with a proper name in my example app target, the above test passes. but
Question
What is the correct way of testing the core data model of a framework?
To run a test, you need to double-click on the test or test fixture name in the Test Runner window. You may also use a context menu option Run, right-click on any item in the test tree to have it (with all its children if any) run.
Core Data is a framework that you use to manage the model layer objects in your application. It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.
Writing Unit Test Cases in Swift With an ExampleUnit test cases run with the testing target. Always check if you have a unit test target or not, if not, then add it. Then under this target, you need to create a new test case file. You will use this new file for writing test cases.
Have you tried loading the Core Data model from the framework bundle?
let managedObjectModel = NSManagedObjectModel.mergedModel(from: nil)
Then you won't need to add it to your test target
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With