如何在IOS中使用雪松测试http请求块

时间:2018-06-04 07:36:27

标签: ios cedar-bdd

我想测试一个名为BookService的类,其方法是获取书籍信息列表。 我应该怎样做才能覆盖成功阻止和失败阻止? 这是我的方法代码:

-(void)getRequestWithURL:(NSString *)urlStr withKey:(NSString *)keyWord completion:(void (^)(NSMutableArray *data))complete{
if(manager==nil)
    manager = [AFHTTPSessionManager manager];
NSLog(@"%@",keyWord);
NSMutableArray *datas = [NSMutableArray new];
NSDictionary *dict=@{
                     @"q":keyWord,
                     @"count":@10
                     };

[manager GET:urlStr parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
    //NSMutableArray *books=[NSMutableArray new];
    NSArray *json= responseObject[@"books"];

    for(id book in json){
        BookInfo *b = [[BookInfo alloc]initWithJson:book];
        NSLog(@"%@",b.author[0]);
        [datas addObject:b];
    }
    complete(datas);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
    NSLog(@"返回失败");
    NSLog(@"%@",error);
    complete(nil);
}];

}

这是我的雪松测试代码

SPEC_BEGIN(BookServiceSpec)

describe(@"BookService", ^{ __block BookService *bookService; __block AFHTTPSessionManager *manager; __block UITableView *tableView; __block NSMutableArray *data; __block NSString *key; __block NSString *url; beforeEach(^{ tableView = [[UITableView alloc]init]; data = [[NSMutableArray alloc]init]; }); describe(@"test bookService", ^{ context(@"get book success", ^{ beforeEach(^{ manager = fake_for([AFHTTPSessionManager class]); manager stub_method(@selector(GET:parameters:progress:success:failure:)); bookService = [[BookService alloc]initWithManager:manager]; url = @"https://api.douban.com/v2/book/search"; key=@"java"; //bookService stub_method(@selector(getRequestWithURL:withKey:completion:)); }); it(@"should manager not be nil", ^{ [bookService getRequestWithURL:url withKey:key completion:^(NSMutableArray *data) { bookService should have_received("getRequestWithURL:withKey:completion"); }]; }); });

SPEC_END

0 个答案:

没有答案