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