【问题标题】:How to write simple unit tests to test the parsing of a JSON?如何编写简单的单元测试来测试 JSON 的解析?
【发布时间】:2016-03-10 13:58:24
【问题描述】:
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:url] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    if (error) {
        NSLog(@"Error");
    } else {
        NSError *e = nil;
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

        if (!jsonDict) {
            NSLog(@"Error parsing JSON: %@", e);
        } else {


        }
    }
}];

你好,

我正在尝试写一个简单的单元测试来检查json的解析是否成功?

我没有单元测试经验。

谢谢

【问题讨论】:

    标签: ios objective-c json unit-testing


    【解决方案1】:

    如果你想测试解析器方法。然后你可以在测试类中创建一个虚拟的 jsonDict。用那个 jsonDict 调用你的解析器方法。

    -(void) testParserMethod {
            // jsonDict = {} // fill according to your method need
            // let say our parser method require a dictionary containing name and age. and set our object. then we can create a dict like this.
           NSDictionary jsonDict= @{ @"name" : @"name", 
                    @"age" : @"age",
                  };
            YourObject object = [YourParserClass parseMethed:jsonDict]
    
            XCTAssertEqual(object.name, jsonDict[@"name"])
            XCTAssertEqual(object.age, jsonDict[@"age"])
    }
    

    如果使用我们提供的虚拟 jsonDict 正确设置对象。那么测试用例就会通过。

    【讨论】:

    • 嘿,你说的 dummy jsonDict 是什么意思?该字典应该包含任何内容还是空白字典?
    • dummy jsonDict 将包含一些您期望来自服务器的数据。在单元测试中,我们不包括服务器。所以我们只是硬编码我们的字典来测试我们的方法。
    • setUp 和 tearDown 方法呢?不需要?
    • 如何将 jsonDict 传递给您的方法?例如,我得到了所需 NSDictionary 的响应,我想将它与标准具字典进行比较?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 2012-02-03
    • 2019-01-28
    • 2015-01-16
    • 1970-01-01
    相关资源
    最近更新 更多