一个具有等待条件满足的能力的同步构造。
可以与任何测试框架一起使用,包括 XCTest、SenTestingKit、expecta 等。
@interface APIClientTests : XCTestCase
@property (nonatomic, strong, readwrite) NSURLSession *URLSession;
@end
@implementation APIClientTests
- (void)setUp {
self.URLSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
}
- (void)testAPIEndpoint {
__block NSDictionary *JSON = nil;
__block TRVSMonitor *monitor = [TRVSMonitor monitor];
[[self.URLSession dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://127.0.0.1:8000"]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
JSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
[monitor signal];
}] resume];
[monitor wait];
XCTAssert(JSON);
XCTAssertEqualObjects(@"1", JSON[@"id"]);
XCTAssertEqualObjects(@"travis jeffery", JSON[@"name"]);
}
- (void)testAPIEndpoints {
__block NSDictionary *personJSON, *twitterJSON;
__block TRVSMonitor *monitor = [[TRVSMonitor alloc] initWithExpectedSignalCount:2];
NSURL *baseURL = [NSURL URLWithString:@"http://127.0.0.1:8000"];
[[self.URLSession dataTaskWithRequest:[NSURLRequest requestWithURL:baseURL] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
personJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
[self.URLSession dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:personJSON[@"id"] relativeToURL:baseURL]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
twitterJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
[monitor signal];
}];
[monitor signal];
}] resume];
[monitor wait];
XCTAssert(personJSON);
XCTAssert(twitterJSON);
XCTAssertEqualObjects(@"travis jeffery", personJSON[@"name"]);
XCTAssertEqualObjects(@"travisjeffery", twitterJSON[@"user_name"]);
}
@end
在 TRVSEventSource 的测试中也很可能看到实际使用。