0

I want to test a class named BookService with a method to get a list of book info. What should I do to coverage both success block and failure block ? Here is my method code:

-(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);
}];

}

And here is my test code with cedar


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

陆飞鹏
  • 9
  • 1
  • Easiest is use some mocking library like Mockingjay to create stub for your response, then can get with the exact response you wanted to happen – Tj3n Jun 04 '18 at 08:32
  • Thank you for your suggestion. But I have to use cedar and I don't know how to mock response really because there is not so many samples in wiki.So did you mean that I can use other mocking library to test this method? – 陆飞鹏 Jun 05 '18 at 06:04

0 Answers0