简体   繁体   English

如何控制UIWebView的loadRequest的加载结果?

[英]How to control the loading result of UIWebView's loadRequest?

I have two tests which depend on the success and failure status of loadRequest method(Some code to be verified in the delegate methods). 我有两个测试,取决于loadRequest方法的成功和失败状态(某些代码需要在委托方法中进行验证)。

I want to verify the code in delegate methods without actually opening a web view evening without connecting to internet. 我想验证委托方法中的代码,而无需在没有连接互联网的情况下实际打开网络视图。 How can I achieve it? 我该如何实现?

Thanks a lot 非常感谢

edited: 编辑:

Maybe a mock object for UIWebView? 也许是UIWebView的模拟对象?

Just use AFNetworking and set it up like this: 只需使用AFNetworking并按如下所示进行设置即可:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

You can then know if the load is successful or not. 然后,您可以知道加载是否成功。 If your website always returns a 200 status code you can then just add an if / then block in the success block. 如果您的网站始终返回200状态代码,则只需在成功代码块中添加if / then块。

OCMock is an Objective-C mocking framework that allows full mocking of classes, partial mocking of objects, as well as expectations and method stubbing. OCMock是一个Objective-C 模拟框架,允许对类进行完全模拟 ,对对象进行部分模拟 ,以及期望和方法存根。

To mock a UIWebView, you would just need to do 要模拟UIWebView,您只需要做

id webViewMock = [OCMockObject mockForClass:[UIWebView class]];

You could then set up expectations: 然后,您可以设置期望:

[[[webViewMock expect] andDo:^(NSInvocation *) {
    // Call your failure or success block
}] someMethodWithArgs:OCMOCK_ANY];

And inject your mock somewhere it can intercept the right calls. 并将您的模拟程序注入可以拦截正确呼叫的位置。

You should also call 你也应该打电话

[webViewMock verify];

to make sure the expected method was invoked 确保调用了预期的方法

I've made one object that conforms to UIWebViewDelegate and set it to UIWebView's delegate, the code is similar to the follows: 我已经制作了一个符合UIWebViewDelegate的对象并将其设置为UIWebView的委托,代码类似于以下内容:

@interface MyObject : Object <UIWebViewDelegate>
...
@end

...

MyObject myObject = [[MyObject alloc] init];
webView.delegate = myObject;

And I can trigger the delegate methods manually: 我可以手动触发委托方法:

[myObject webView:webView didFailLoadWithError:mockError];
[myObject webViewDidFinishLoad:webView];

And Of course, the webView is a mocked object. 当然,webView是一个模拟对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM