2011-11-25 102 views
6

我有數據iOS應用程序使用NSCoding和更精確的NSKeyedArchiver堅持。此應用程序已在App Store上提供。如何單元測試NSCoding?

我工作的應用程序和數據模型應該改變的2版本。所以我需要處理數據模型遷移。我希望它由單元測試覆蓋。

在我的測試中,我要動態地生成與舊的數據模型,推出移民持續的數據,看看是否一切順利。

目前,歸檔對象看起來是這樣的:

MyDataModelObject *object = .... 
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; 
[archiver encodeObject:object forKey:key]; 
[archiver finishEncoding]; 

的問題是,MyDataModelObject可能會被重新分解,甚至在應用程序的版本2中刪除。所以我不能在我的測試中使用這個類來生成「舊版本檔案」。

有沒有辦法模擬不使用這個類的encodeWithCoder:方法做了什麼?


我想實現如下

- testMigrationFrom_v1_to_v2 { 
    // simulate an archive with v1 data model 
    // I want this part of the code to be as simple as possible 
    // I don't want to rely on old classes to generate the archive 
    NSDictionary *person = ... // { firstName: John, lastName: Doe } 
    NSDictionary *adress = ... // { street: 1 down street, city: Butterfly City } 
    [person setObject:adress forKey:@"adress"]; 

    // there's something missing to tell the archiever that: 
    // - person is of type OldPersonDataModel 
    // - adress is of type OldAdressDataModel 

    [archiver encodeObject:person forKey:@"somePerson"]; 
    // at this point, I would like the archive file to contain : 
    // a person object of type OldPersonDataModel, that has an adress object of type OldAdressModel 

    NewPersonModel *newPerson = [Migration readDataFromV1]; 

    // assertions 
    NSAssert(newPerson.firstName, @"John"); 
    NSAssert(newPerson.lastName, @"Doe"); 
} 

回答

1

我真的不明白你的問題,所以我會給你兩個答案:

您可以預載的一個實例NSDictionary帶有您將用於舊類的鍵/值,並創建一個新的鍵控歸檔器,循環遍歷所有鍵並存檔。

您還可以得到任何類的-attributeKeys方法來獲取所有的鍵,然後可能使用此代碼來模擬存檔:

NSKeyedArchiver *archive = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; 
[archiver encodeObject:object forKey:key]; 
for (NSString *key in object.attributeKeys) { 
    [archive encodeObject:[object valueForKey:key] forKey:key]; 
} 
[archive finishEncoding]; 

在遷移數據來看,的NSKeyedArchiver有方法-setClass:forClassName:,你可以支持新對象中的所有舊鍵以將它們轉換爲不同的屬性。

+0

謝謝您的回答,我編輯的問題,使之更加清晰的(希望) – David

+1

attributeKeys是NSClassDescription,這不iOS上存在的一部分。 – quellish