我刚刚开始使用存根请求来测试对 iOS 外部 API 的异步调用。我目前坚持使用以下代码,我无法弄清楚什么不起作用。
我想要实现的非常简单的事情是,如果我从网站获得 200 响应,我将视图的背景颜色更改为绿色,否则我将其染成红色。
在- (void)viewDidLoad
我的视图控制器的方法中,我调用了以下方法:
- (void)checkConnectivity {
NSURL *url = [NSURL URLWithString:@"http://www.example.com/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
self.currentBackgroundColor = [UIColor greenColor];
[self changeToBackgroundColor:self.currentBackgroundColor];
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
self.currentBackgroundColor = [UIColor redColor];
[self changeToBackgroundColor:self.currentBackgroundColor];
});
}
}];
[task resume];
}
- (void)changeToBackgroundColor:(UIColor *)color {
self.view.backgroundColor = color;
}
我的 Kiwi 规格如下所示:
#import "Kiwi.h"
#import "Nocilla.h"
#import "TWRViewController.h"
@interface TWRViewController ()
@property (strong, nonatomic) UIColor *currentBackgroundColor;
- (void)checkConnectivity;
- (void)changeToBackgroundColor:(UIColor *)color;
@end
SPEC_BEGIN(KiwiSpec)
describe(@"When the app launches", ^{
context(@"check if internet is available", ^{
beforeAll(^{
[[LSNocilla sharedInstance] start];
});
afterAll(^{
[[LSNocilla sharedInstance] stop];
});
afterEach(^{
[[LSNocilla sharedInstance] clearStubs];
});
it(@"should display a green background if there is connectivity", ^{
stubRequest(@"GET", @"http://www.example.com/").andReturn(200);
TWRViewController *vc = [[TWRViewController alloc] initWithNibName:@"TWRViewController" bundle:nil];
[vc checkConnectivity];
[[vc.currentBackgroundColor shouldEventually] equal:[UIColor greenColor]];
});
});
});
SPEC_END
我不知道我做错了什么,但它一直在失败。任何想法?