2016-04-15 68 views
1

當我運行測試時,可以創建新的臨時核心數據庫嗎?比它出現在模擬器單元測試的核心數據臨時數據庫

import XCTest 
@testable import TestProj 

class ChangeWishListTests: XCTestCase { 
    func testSaveWishList() { 
      self.wishList = self.changeWishListVC?.saveWishList(title: "Test wish list", 
                   desc: "My description", 
                   wishlistType: WishListType.Shared, 
                   hidden: false) 
      XCTAssertNotNil(wishList, "Wishlist not created.") 
     } 
} 

因爲我有一個問題,當我運行我的測試,我創建的心願。或者如果這是不可能的,我該如何管理我的假物體。

回答

2

是的,您可以但是爲了做到這一點,您必須能夠更改(告訴VC)用於執行核心數據操作的管理對象上下文。通過這樣做,您可以在用戶測試中使用測試受管對象,並在生產應用程序代碼中測試受管對象。

通過測試管理對象上下文我的意思是隻在內存中不保存任何東西到光盤上存儲數據的一個 - 在那種情況下的測試的不同發射之間不會保留執行的操作的結果。

創建僅存儲在內存中的數據管理對象上下文很簡單:

let managedObjectModel = NSManagedObjectModel.init(contentsOfURL: modelURL) 
    var managedObjectContext = NSManagedObjectContext.init(concurrencyType: .MainQueueConcurrencyType) 
    managedObjectContext.persistentStoreCoordinator = NSPersistentStoreCoordinator.init(managedObjectModel: managedObjectModel) 

    var error: NSError? 
    let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true]; 
    let persistentStore = try! managedObjectContext.persistentStoreCoordinator?.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: options) 

最簡單的方法來給自己可能使用測試管理對象上下文是使用依賴注入。創建VC的初始化程序,將託管對象上下文作爲參數 - 在測試代碼中注入測試託管對象上下文,並在生產代碼中注入普通託管對象上下文。