网络请求的单元测试与普通单元测试的区别
网络请求为异步方式进行,发起请求之后就继续向下执行,无论请求是否成功,单元测试都会完成
单元测试中对于异步进行的方法的处理
在单元测试中遇到异步方式时,执行完异步方法后阻塞当前线程,等异步方法执行完成后,再向下执行,校验返回数据
Demo 如何阻塞线程,等待数据返回
1、声明一个XCTestExpectation对象
2、强引用该XCTestExpectation对象。(用于在请求成功的回调方法中使用该对象触发指定方法)
3、执行异步网络请求方法
4、等待数据成功返回
#import <UIKit/UIKit.h> #import <XCTest/XCTest.h> #import "NSObject+YPApiService.h" #import "YPApiServiceKit.h" @interface YouPiaoTests : XCTestCase<YPApiServiceKitDataSource> @property (nonatomic,strong) XCTestExpectation *e; @end @implementation YouPiaoTests - (void) testIndexList { // 1 声明XCTestExpectation对象 XCTestExpectation *e = [self expectationWithDescription:@"des"]; // 2 对该对象强引用 self.e = e; // 3 发起网络请求 [self api_Post_IndexList]; // 4 等待 XCTestExpectation对象触发fulfill方法,或超时之后再向下执行 [self waitForExpectationsWithTimeout:10 handler:^(NSError * _Nullable error) { NSLog(@"%@",error); }]; } // 网络请求响应成功的回调方法 - (void)serverResponseSuccess:(YPBaseModel *)responseModel { NSLog(@"%@",responseModel); [self.e fulfill]; } @end |
相关方法
通过发送通知来触发继续执行
声明
self expectationForNotification:@"RSBaseTest" object:nil handler:nil];
等待执行
[self waitForExpectationsWithTimeout:30 handler:nil];} while (0);
发送通知
[[NSNotificationCenter defaultCenter]postNotificationName:@"RSBaseTest" object:nil];