iphoneobjective-cmultithreadingautomated-testsgoogle-toolbox-for-mac

iPhone : Waiting for a webview to load in automated test


I'm using Google Toolbox for Mac to test my application. The test I'm working on checks that when a shake event, a dedicated controller sends a message to a webview, and that the HTML page responds correctly by doing a "screenshot".

The problem I have is that it doesn't work if the webview doesn't have time to load. So I use a little trick to "pause" the test, and wait for the webview to load :

#define allowedTimeToLoadALocalFileInWebView 5.5

NSDate *start = [NSDate date];

while (
// webViewLoaded is false at the beginning
///the Test class is a delegate of the webview, and webviewLoaded is set to true when - (void)webViewDidFinishLoad:(UIWebView *)webView is called 
     !webViewLoaded
    &&
    [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]
    && 
    (-[start timeIntervalSinceNow]) < allowedTimeToLoadALocalFileInWebView
    );

The strange thing is that it doesn't work if I use allowedTimeToLoadALocalFileInWebView smaller than 5 seconds, which is very long for a local file to be loaded...

Moreover, later on, I perform javascript on the webView with the

stringByEvaluatingJavaScriptFromString:

, and I have to wait for an animation to be performed, so I use the same code :

NSDate *restart = [NSDate date];

while (  [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]
       && 
       (-[restart timeIntervalSinceNow]) < allowedTimeToLoadALocalFileInWebView
       );

And this take something like 50 seconds ! (the animation doesn't even last a second...)

I think the (-[restart timeIntervalSinceNow]) < allowedTimeToLoadALocalFileInWebView is useless since it appears that runMode:beforeDate: takes more time than my allowedTimeToLoadALocalFileInWebView in the second case.

I also tried to use

[NSThread sleepForTimeInterval:allowedTimeToLoadALocalFileInWebView];

But this prevents the results to be visible.

Do you have any idea on why loading the webview takes so long to load a local file ? And another way to wait for the animation without using runMode:beforeDate: ?

Thank you


Solution

  • Ok, so the problem was to run the current loop for [NSDate distantFuture]. I solved the issue by waiting like this :

    while (! webViewLoaded && (-[start timeIntervalSinceNow]) < timeOut) {
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:allowedTimeToLoadALocalFileInWebView]];
    }
    

    The timeout is for the test to fail if the webView never loads (we never know) since we launch those test automatically, we don't want the server to run in an infinite loop. The tests used to take more than a minute, now 3.5 seconds !