【问题标题】:RestKit: Testing object mapping, 'failure when mapping from...'RestKit:测试对象映射,“从...映射时失败”
【发布时间】:2023-03-29 06:05:02
【问题描述】:

正如这个问题的标题所示,我正在使用 RestKit,我想使用内置测试类来测试我的对象映射。我编写了一个小型应用程序,它从(本地)web api 获取用户对象作为 json。这部分有效,但是,我的测试用例告诉我它没有 - 嗯!

我正在关注 Blake Watters Unit Testing With RestKit Guide,但我无法成功。让我再次澄清一下,实际的应用程序工作正常(我能够毫无问题地将 json 从 API 映射到 User 对象),但是测试用例失败并出现如下所示的错误。因此,不知何故,我怀疑我的测试是错误的。

这里有一些代码:

错误信息

<RKMappingTest: 0xa242130>: failure when mapping from {
user =     {
    "first_name" = Kasper;
    id = 21;
    "last_name" = Fueled;
};
} to <User: 0xa23d730> with mapping <RKObjectMapping:0xa23d250 objectClass=User keyPath mappings => (
"RKObjectKeyPathMapping: id => userID",
"RKObjectKeyPathMapping: first_name => first_name",
"RKObjectKeyPathMapping: last_name => last_name",
)>. 

我注意到没有引用 id 键,而 first_name 和 last_name 是,但我不确定它是否有任何区别。

user.json(更新:去掉逗号)

{ "user": {
       "id":21,
       "first_name":"Kasper",
       "last_name":"Fueled"
       }
}

user.json(旧)

{ "user": {
       "id":21,
       "first_name":"Kasper",
       "last_name":"Fueled",
       }
}

用户.h

@property (strong, nonatomic) NSNumber *userID;
@property (strong, nonatomic) NSString *first_name;
@property (strong, nonatomic) NSString *last_name;

用户映射

+ (RKObjectMapping *)objectMapping {
    return [RKObjectMapping mappingForClass:[User class] usingBlock:^(RKObjectMapping *mapping) {
        [mapping mapKeyPath:@"id" toAttribute:@"userID"];
        [mapping mapKeyPath:@"first_name" toAttribute:@"first_name"];
        [mapping mapKeyPath:@"last_name" toAttribute:@"last_name"];
    }];
}

测试用例

- (void)testMapping {
    id parsedJSON = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"];
    RKMappingTest *test = [RKMappingTest testForMapping:[User objectMapping] object:parsedJSON];

    [test expectMappingFromKeyPath:@"user.first_name" toKeyPath:@"first_name"];

    STAssertNoThrow([test verify], nil);
}

按照 Blake 指南中的说明创建夹具。

【问题讨论】:

    标签: ios unit-testing restkit


    【解决方案1】:

    好吧,虽然很尴尬,但我不会发布我的问题的解决方案。我的假设是正确的,即我的测试设置有问题,而不是我正在测试的代码。事实证明,我的 json 夹具中最后一个键值对的末尾有一个逗号。我手工编写了 json 夹具,而不是直接从我的 API 的输出中复制它。因此,吸取的教训必须是:

    复制/粘贴您尝试测试对象映射的 json 输出到您的夹具文件中。不要只是手动输入 - 可能会出现拼写错误等情况。

    希望我是社区中唯一一个这样做(或做过!)这样做的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多