YTTFakeServer是NSURLProtocol
的子类。它为NSURLConnection
或NSURLSession
请求返回模拟HTTP响应。
YTTFakeServer为HTTP请求提供模拟响应。在最简单的用法中,您将在项目中放置捆绑包,并使用YTTFakeServerConfiguration
进行配置。YTTFakeServer通过请求路径从捆绑包中查找响应数据,并返回包含数据的响应。您还可以使用YTTFakeServerDelegate
设置HTTPHeader和HTTP状态。
YTTFakeServer不仅有助于测试代码。因为它不需要更改测试或生产中请求部分的代码,所以它有助于HTTP请求的模拟开发。
YTTFakeServer是NSURLProtocol
的子类。您还可以用它进行真实的连接mitmProxy。
要运行示例项目,克隆仓库,然后首先从示例目录运行pod install
。
首先,使用YTTFakeServerConfiguration
进行配置。您可以设置自定义捆绑包。
[YTTFakeServer configure:^(YTTFakeServerConfiguration *configuration) {
configuration.hosts = @["http://your.host/"];
configuration.delegate = self; // delegate
configuration.delay = 1.0; // delay interval
configuration.resourceBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"YourCustomBundle" ofType:@"bundle"]];
configuration.resourceFileExtension = @"json"; // resource type
}];
例如,如果您想要设置路径为api/foo/bar
的响应json,您只需设置包含api/foo/bar.json
的捆绑包。这非常简单。
YTTFakeServerConfiguration
还有一些其他选项。
schemes
(默认为http, https)ignoringFileExtentions
(默认为.jpg, .png, .css, .js)cacheStoragePolicy
(默认为NSURLCacheStorageNotAllowed
)enableReachabilityCheck
(默认为YES)如果您使用NSURLConnection
,则需要像这样注册NSURLProtocol
。
[NSURLProtocol registerClass:[YTTFakeServer class]];
如果您使用NSURLSession
,则使用NSURLSessionConfiguration
。
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.protocolClasses = @[[YTTFakeServer class]];
YTTFakeServerDelegate
提供了一些使用API。
这是自定义响应示例。
- (YTTFakeServerResponse *)YTTFakeServerClient:(id<NSURLProtocolClient>)client responseForRequest:(NSURLRequest *)request
{
NSString *path = request.URL.path;
if ([path isEqualToString:@"/api/auth"]) {
NSDictionary *param = [NSURLProtocol propertyForKey:@"parameters" inRequest:request];
if (![param[@"password"] isEqualToString:@"1234"]) {
NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"YTTFakeServer" ofType:@"bundle"]];
NSData *responseData = [[NSData alloc] initWithContentsOfFile:[bundle pathForResource:@"auth_error" ofType:@"json" inDirectory:@"api"]];
return [[YTTFakeServerResponse alloc] initWithURL:request.URL headers:request.allHTTPHeaderFields status:400 responseData:responseData];
}
}
return nil;
}
还支持更多几个代理方法。所有方法都是可选的。请查看示例或文档。
如果您使用NSURLSession,并想检查HTTPBody,请使用NSURLProtocol:setProperty:forKey:inRequest
。
请查看示例和问题AliSoftware/OHHTTPStubs,问题52
它依赖于Reachability以及一个选项。因此,如果您想启用它,也请添加SystemConfiguration.framework
。
git checkout -b my-new-feature
git commit -am '添加一些功能'
git push origin my-new-feature
YTTFakeServer受到了以下文章和库的启发。
yatatsu,[email protected]
YTTFakeServer遵循MIT授权许可。有关更多信息,请参阅LICENSE文件。