我有一个需要序列化和反序列化的小数据对象。假设它被称为 WeatherDetails ,它看起来像这样:

WeatherDetails.h

@interface WeatherDetails : NSObject <NSCoding>
{
@private

@protected
}

#pragma mark - Properties

@property (nonatomic, copy) NSString *weatherCode;
@property (nonatomic, copy) NSString *weatherDescription;

@end

WeatherDetails.m
#import "WeatherDetails.h"

@implementation WeatherDetails

NSString *const WEATHER_DETAILS_WEATHER_CODE_KEY = @"s";
NSString *const WEATHER_DETAILS_WEATHER_DESCRIPTION_KEY = @"sT";

#pragma mark - Initialization, NSCoding and Dealloc

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];

    _weatherCode = [aDecoder decodeObjectForKey:@"weatherCode"];
    _weatherDescription = [aDecoder decodeObjectForKey:@"weatherDescription"];

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_weatherCode forKey:@"weatherCode"];
    [aCoder encodeObject:_weatherDescription forKey:@"weatherDescription"];
}

目前我的测试是这样的;
#import <XCTest/XCTest.h>
#import <OCMock/OCMock.h>
#import "WeatherDetails.h"
@interface WeatherDetailsTests : XCTestCase

@end

@implementation WeatherDetailsTests

- (void)testThatWeatherCodeIsEncoded
{
    WeatherDetails *details = [[WeatherDetails alloc] init];
    [details setWeatherCode:@"A"];

    NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:details];

    WeatherDetails *unarchive = [NSKeyedUnarchiver unarchiveObjectWithData:archive];

    XCTAssertEqualObjects(@"A", [unarchive weatherCode]);
}

- (void)testThatWeatherDescriptionIsEncoded
{
    WeatherDetails *details = [[WeatherDetails alloc] init];
    [details setWeatherDescription:@"A"];

    NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:details];

    WeatherDetails *unarchive = [NSKeyedUnarchiver unarchiveObjectWithData:archive];

    XCTAssertEqualObjects(@"A", [unarchive weatherDescription]);
}

我有一种直觉,这种测试所有属性是否正确编码的方法并不是真正的最佳方法,因为存在重复,但我真的想不出更好的方法。有没有人对我改进这个有建议?

最佳答案

您真正想要测试的是对象在存档之前和之后是否相同。

WeatherDetails 中实现一个方法来比较对象(或覆盖 isEqual: )。

- (BOOL)isEqualToWeatherDetails:(WeatherDetails *)details
{
    if (![details isKindOfClass:[WeatherDetails class]]) return NO;
    return [self.weatherCode == details.weatherCode && self.weatherDescription isEqualToString:details.weatherDescription];
}

然后你可以一次完成所有的相等比较:
- (void)testNSCoder
{
    WeatherDetails *details = [[WeatherDetails alloc] init];
    [details setWeatherCode:@"A"];
    details.weatherDescription = @"Cloudy";

    NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:details];

    WeatherDetails *unarchive = [NSKeyedUnarchiver unarchiveObjectWithData:archive];

    XCTAssertTrue([details isEqualToWeatherDetails:unarchive]);
}

如果你覆盖了 isEqual: 那么你可以比较这样做:
XCTAssertEqualObjects(details, unarchive);

Apple 倾向于添加其他方法( isEqualToArray:isEqualToDictionary: )。 isEqual: 被 NSSet 和 NSDictionary 等集合使用

关于ios - 如何测试实现 NSCoding 的简单数据对象类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32121502/

10-12 06:50