【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
前言
单元测试对于任何的应用或者系统都是必要的,只是我们在开发的时候,大多数都忽略它的重要性与必要性;单元测试可以尽可能的保证项目的质量以及业务流程的完整性,减少bug的产生。
本例使用XCTest,xcode自带测试框架;
(一)测试异步(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
待续;
来源:oschina
链接:https://my.oschina.net/u/1450995/blog/787174