简体   繁体   中英

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).

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?

Just use AFNetworking and set it up like this:

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.

OCMock is an Objective-C mocking framework that allows full mocking of classes, partial mocking of objects, as well as expectations and method stubbing.

To mock a UIWebView, you would just need to do

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:

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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