22

我正在编写一个需要从 Web 服务器获取一些数据的 iPhone 应用程序。我NSURLConnection用来执行 HTTP 请求,效果很好,但是在响应具有 HTTP 错误代码(如 404 或 500)的情况下,我无法对代码进行单元测试。

我使用GTM进行单元测试,使用OCMock进行模拟。

当服务器返回错误时,连接不会调用connection:didFailWithError:委托,而是调用connection:didReceiveResponse:, connection:didReceiveData:, and connectionDidFinishLoading:。我目前正在检查响应中的状态代码,并在状态代码看起来像错误时connection:didReceiveResponse:调用连接以防止被调用,从而报告成功的响应。cancelconnectionDidFinishLoading:

提供静态存根NSURLConnection很简单,但我希望我的测试在调用模拟连接的方法之一时改变它的行为。具体来说,我希望测试能够判断代码何时调用cancel了模拟连接,因此测试可以停止调用connection:didReceiveData:connectionDidFinishLoading:委托。

有没有办法让测试判断是否cancel已在模拟对象上调用?有没有更好的方法来测试使用的代码NSURLConnection?有没有更好的方法来处理 HTTP 错误状态?

4

1 回答 1

43

有没有更好的方法来处理 HTTP 错误状态?

我认为你在正确的轨道上。我使用类似于以下代码的东西,我在这里找到了:

if ([response respondsToSelector:@selector(statusCode)])
{
    int statusCode = [((NSHTTPURLResponse *)response) statusCode];
    if (statusCode >= 400)
    {
        [connection cancel];  // stop connecting; no more delegate messages
        NSDictionary *errorInfo
          = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:
            NSLocalizedString(@"Server returned status code %d",@""),
            statusCode]
                                        forKey:NSLocalizedDescriptionKey];
        NSError *statusError
          = [NSError errorWithDomain:NSHTTPPropertyStatusCodeKey
                                code:statusCode
                            userInfo:errorInfo];
        [self connection:connection didFailWithError:statusError];
    }
}

这会取消连接,并调用connection:didFailWithError:以使 http 错误代码的行为与任何其他连接错误完全相同。

于 2009-04-24T14:49:13.950 回答