2011-11-25 111 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