在测试用例中,我定义了一个testModelConvert
  方法用来测试模型跟json之间的转换是否正确:
- (void)testModelConvert
{
NSString * json = @"{"name":"SindriLin","age":22,"flags":987654321}";
NSMutableDictionary * dict = [[NSJSONSerialization JSONObjectWithData: [json dataUsingEncoding: NSUTF8StringEncoding] options: kNilOptions error: nil] mutableCopy];
LXDTestsModel * model = [[LXDTestsModel alloc] initWithDictionary: dict];
XCTAssertNotNil(model);
XCTAssertTrue([model.name isEqualToString: @"SindriLin"]);
XCTAssertTrue([model.age isEqual: @(22)]);
XCTAssertEqual(model.flags, 987654321);
XCTAssertTrue([model isKindOfClass: [LXDTestsModel class]]);
model = [LXDTestsModel modelWithName: @"Tessie" age: dict[@"age"] flags: 562525];
XCTAssertNotNil(model);
XCTAssertTrue([model.name isEqualToString: @"Tessie"]);
XCTAssertTrue([model.age isEqual: dict[@"age"]]);
XCTAssertEqual(model.flags, 562525);
NSDictionary * modelJSON = [model modelToDictionary];
XCTAssertTrue([modelJSON isEqual: dict] == NO);
dict[@"name"] = @"Tessie";
dict[@"flags"] = @(562525);
XCTAssertTrue([modelJSON isEqual: dict]);
}
  例二
  由于单元测试是在主线程中进行的,因此异步操作的测试在执行完毕之前,往往已经结束了。有两种方法解决
  采用while()的方式无限循环等待
//waitForExpectationsWithTimeout是等待时间,超过了不再等待往下执行。
#define WAIT do {
[self expectationForNotification:@"RSBaseTest" object:nil handler:nil];
[self waitForExpectationsWithTimeout:30 handler:nil];
} while (0)
#define NOTIFY [[NSNotificationCenter defaultCenter]postNotificationName:@"RSBaseTest" object:nil]
-(void)testRequest{
// 1.获得请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",nil];
// 2.发送GET请求
[mgr GET:@"http://www.weather.com.cn/adat/sk/101110101.html" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"responseObject:%@",responseObject);
XCTAssertNotNil(responseObject, @"返回出错");
NOTIFY //继续执行
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error:%@",error);
XCTAssertNil(error, @"请求出错");
NOTIFY //继续执行
}];
WAIT  //暂停
}
  另一种异步测试实现 使用GCD信号量
- (void)downloadImageURLWithString:(NSString *)URLString
{ dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURL *url = [NSURL URLWithString:URLString];
__unused Photo *photo = [[Photo alloc] initwithURL:url
withCompletionBlock:^(UIImage *image, NSError *error) {
if (error) {
XCTFail(@"%@ failed. %@", URLString, error);
}
dispatch_semaphore_signal(semaphore);
}];
dispatch_time_t timeoutTime = dispatch_time(DISPATCH_TIME_NOW, kDefaultTimeoutLengthInNanoSeconds);
if (dispatch_semaphore_wait(semaphore, timeoutTime)) {
XCTFail(@"%@ timed out", URLString);
}
}
  借鉴 开源项目
  常用的第三方框架例如YYModel、AFNetworking、Alamofire等等框架中也有对框架自身编写的单元测试,学习仿写这些单元测试也是快速提升自己的一种手段。