Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to test core data model used in a framework in swift

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?

like image 446
Jafar Khoshtabiat Avatar asked Oct 03 '19 07:10

Jafar Khoshtabiat


People also ask

How do I run a test 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.

Is Core Data a framework?

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.

How do you write a test case in Swift?

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.


1 Answers

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

like image 57
Joakim Danielson Avatar answered Oct 05 '22 14:10

Joakim Danielson