前言api
單元測試對於任何的應用或者系統都是必要的,只是咱們在開發的時候,大多數都忽略它的重要性與必要性;單元測試能夠儘量的保證項目的質量以及業務流程的完整性,減小bug的產生。xcode
本例使用XCTest,xcode自帶測試框架;app
(一)測試異步(AFNetworking異步請求);框架
(1)AFNetworking異步請求後臺api,返回數據;異步
#import <Foundation/Foundation.h> @interface TestService : NSObject + (void)testPostWy:(void (^)(id responseObject))sucess failure:(void (^)(id error))failure; @end #import "TestService.h" #import "AFApiDotNet.h" @implementation TestService + (void)testPostWy:(void (^)(id))sucess failure:(void (^)(id))failure { AFHTTPSessionManager *manager = [AFApiDotNet httpClient]; [manager GET:@"http://c.m.163.com/recommend/getSubDocPic?from=toutiao&prog=LMA1&open=&openpath=&fn=1&passport=&devId=5JQZG5PgwYinhJwpDtJKli2CqJrnjKAhdzTBA6zNHRZPOwRoIXUmsUYPMV3I%2B%2FIj&offset=0&size=10&version=17.2&spever=false&net=wifi&lat=BA%2FHUi%2FT6BcektiKQUOupg%3D%3D&lon=%2B6UXFqODkP%2FBHvMCgZrokw%3D%3D&ts=1479041109&sign=h4oxEfd8zdXy69d0MIhyMVWCwvM7uP3pCXYLEYM3yU548ErR02zJ6%2FKXOnxX046I&encryption=1&canal=appstore" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (sucess) { sucess(responseObject); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }]; } @end
(2)XCTestCase單元測試,如下testNetworkOpening方法,使用XCTestExpectation類,進行異步代碼的測試;單元測試
#import <XCTest/XCTest.h> #import "TestService.h" @interface TestVCTests : XCTestCase @end @implementation TestVCTests XCTestExpectation *networkSuccessExpectation; - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } - (void)testPerformanceExample { // This is an example of a performance test case. [self measureBlock:^{ // Put the code you want to measure the time of here. for (int i = 0; i < 20; i++) { NSLog(@"test -- %d", i); } }]; } - (void)testNetworkOpening { networkSuccessExpectation = [self expectationWithDescription:@"api open"]; [TestService testPostWy:^(id responseObject) { id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil]; if ([result isKindOfClass:[NSDictionary class]]) { [networkSuccessExpectation fulfill]; } } failure:^(id error) { if ([error isKindOfClass:[NSError class]]) { [networkSuccessExpectation fulfill]; } }]; [self waitForExpectationsWithTimeout:10.f handler:^(NSError * _Nullable error) { NSLog(@"time out"); }]; } @end
待續;測試