iOS で外部 API への非同期呼び出しをテストするためのスタブ要求から始めたところです。現在、次のコードで立ち往生しており、何が機能していないのかわかりません。
私が達成しようとしている非常に単純なことは、Web サイトから 200 応答を受け取った場合、ビューの背景色を緑に変更し、それ以外の場合は赤くすることです。
- (void)viewDidLoad
私のView Controllerのメソッドでは、次のメソッドを呼び出しています:
- (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;
}
私のキウイ仕様は次のようになります。
#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
何が間違っているのかわかりませんが、失敗し続けています。何か案が?