如何unit testingNSCoding?

我有一个iOS应用程序,数据持久使用NSCoding,更确切地说是NSKeyedArchiver。 此应用程序已经在App Store上提供。

我正在处理应用程序的版本2,数据模型应该改变。 所以我需要处理数据模型迁移。 我希望它通过unit testing覆盖。

在我的testing中,我想用旧的数据模型dynamic生成持久数据,启动迁移,看看是否一切顺利。

目前,归档对象如下所示:

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

问题是,MyDataModelObject可能被重新考虑,甚至在应用程序的版本2中被删除。 所以我不能在testing中使用这个类来生成一个“旧版本档案”。

有没有一种方法来模拟不使用这个类的类的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"); } 

我不太了解你的问题,所以我会给你两个答案:

你可以预先加载一个NSDictionary的实例,并用你的旧类使用的键/值创build一个新的键控归档器,循环所有的键并存档。

你也可以得到任何类的-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:并且可以支持新对象中的所有旧键以将它们转换为不同的属性。