我刚开始使用存根请求来测试对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我不知道我做错了什么,但它总是失败。有什么想法吗?
发布于 2014-04-05 03:34:58
似乎你的异步匹配器是不完整的。
您需要使用expectFutureValue包装异步匹配器的主题,如下所示:
[[expectFutureValue(vc.currentBackgroundColor) shouldEventually] equal:[UIColor greenColor]];为了便于将来参考,当您将异步匹配器添加到像BOOL这样的原语时,您需要在上面添加theValue,如下所示:
[[expectFutureValue(theValue(myBool) shouldEventually] beYes];希望能有所帮助
https://stackoverflow.com/questions/21817267
复制相似问题