如何单元测试NSCoding? [英] How to unit test NSCoding?
问题描述
我有一个iOS应用程序,数据持久使用NSCoding和更准确的NSKeyedArchiver。此应用程序已在App Store上提供。
I have an iOS application with data persisted using NSCoding and more precisely NSKeyedArchiver. This application is already available on the App Store.
我正在使用版本2的应用程序,数据模型应该更改。所以我需要处理数据模型迁移。
I'm working on version 2 of the application and the data model should change. So I need to handle data model migration. I want it covered by unit tests.
在我的测试中,我想使用旧的数据模型动态生成持久化数据,启动迁移并查看一切是否正常
目前,归档对象如下所示:
Currently, archiving an object looks like this :
MyDataModelObject *object = ....
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:object forKey:key];
[archiver finishEncoding];
问题是,MyDataModelObject可能在应用程序的版本2中被重新计算甚至删除。所以我不能在测试中使用这个类来生成一个'旧版本的归档'。
The problem is, MyDataModelObject might be re-factored or even deleted in the version 2 of the application. So I can't use this class in my tests to generate an 'old version archive'.
有没有办法模拟在 encodeWithCoder:
不使用此类的类的方法
Is there a way to simulate what is done in the encodeWithCoder:
method of a class without using this class ?
我想要实现的是以下
- 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");
}
推荐答案
你的问题所以我会给你两个答案:
I don't really understand your question so I will give you two answers:
你可以预先加载一个 NSDictionary
您还可以获取任何类的 -attributeKeys
方法获取所有密钥,然后可能使用此代码来模拟归档:
You can also get any class's -attributeKeys
method to get all the keys and then possibly use this code to simulate an archive:
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:
,您可以支持新对象中的所有旧密钥,将其转换为不同的属性。
On the point of migrating data, NSKeyedArchiver has the method -setClass:forClassName:
and you can support all of your old keys in your new object to translate them into different properties.
这篇关于如何单元测试NSCoding?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!