我刚开始使用 stub 请求来测试对 iOS 的外部 API 的异步调用。我目前被以下代码困住了,我无法弄清楚什么不起作用。
我想要实现的非常简单的事情是,如果我从网站收到 200 响应,我将 View 的背景色更改为绿色,否则我将其染成红色。
在我的 View Controller 的 - (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
我不知道我做错了什么,但一直失败。有什么想法吗?
最佳答案
您的异步匹配器似乎不完整。
您需要像这样用 expectFutureValue 包装异步匹配器的主题:
[[expectFutureValue(vc.currentBackgroundColor) shouldEventually] equal:[UIColor greenColor]];
为了将来引用,当您将异步匹配器添加到像 BOOL 这样的基元时,您需要在其上添加 theValue,如下所示:
[[expectFutureValue(theValue(myBool) shouldEventually] beYes];
希望对你有帮助
关于iOS Kiwi + Nocilla - 未能 stub 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21817267/