用于 iOS 测试的模拟服务器。
可以通过 expect
或 stub
注册模拟响应。
[[[server expect] forPath:@"/api/"] andJSONResponseResource:@"fake-response" ofType:@"json"];
Podfile
pod 'NLTHTTPStubServer'
NLTHTTPStubServer.h
。最简单的使用 GHUnit 异步测试用例的例子。服务器 URL 默认为 localhost:12345
。
- (void)testMostSimply {
// Get shared server instance.
server = [NLTHTTPStubServer sharedServer];
// Register fake response for localhost:12345/fake
NSData *data = [@"RESPONSE" dataUsingEncoding:NSUTF8StringEncoding];
[[[server expect] forPath:@"/fake"] andPlainResponse:data];
// GHUnit: Setup async test
[self prepare];
// Access to localhost:12345/fake
__weak id that = self;
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://:12345/fake"]]
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *res, NSData *data, NSError *err) {
// Getting a fake response!
GHAssertEqualStrings(toString(data), @"RESPONSE", nil);
// GHUnit: notify!
[that notify:kGHUnitWaitStatusSuccess];
}];
// GHUnit: wait for status...
[self waitForStatus:kGHUnitWaitStatusSuccess timeout:10];
// Invoked all expects?
[server verify];
}
获取共享实例。
NLTHTTPStubServer *server =[NLTHTTPStubServer sharedServer];
移除所有模拟响应。
[server clear];
[[server expect] forPath:@"/fake"];
注册模拟响应。如果请求 /fake
,服务器将响应此模拟响应。在此设置后,应首先调用测试的功能,然后
[server verify];
如果期望的响应未被调用,验证方法将抛出异常。
[[server stub] forPath:@"/fake"]
stub
类似于 expect
,但是 stub
如果被调用,则存在。verify
忽略通过 stub
注册的响应。
NLTPath
生成复杂的路径。例如,这个请求有两个 GET 参数。
[[server expect] forPath:[NLTPath pathWithPathString:@"/fake" andParameters:@{
@"k1" : @"v1",
@"k2" : @"v2",
}]];
这个请求可以匹配 /fake?k1=v1&k2=v2
或 /fake?k2=v2&k1=v1
。
可以使用 [NLTPath anyValue]
来指定参数的值。
[[server expect] forPath:[NLTPath pathWithPathString:@"/fake" andParameters:@{
@"k1" : [NLTPAth anyValue]
}]];
这个请求可以匹配 /fake?k1=hogeeeeeeee
、/fake?k1=fugaaaaaaaaaa
等。
[[server stub] forPath:@"/fake" HTTPMethodPost];
[[[server stub] forPath:@"/fake"] andStatusCode:200];
[[[server stub] forPath:@"/fake"] andProcessingTime:10.0f];
[[[server expect] forPath:@"/fake" HTTPMethod:@"POST"] andCheckPostBody:^(NSData *postBody) {
NSString *postBodyString = [that toString:postBody];
GHAssertEqualStrings(postBodyString, @"POST_BODY", nil);
}];
[[[server expect] forPath:@"/fake"] and{ContentType}Response...]