Waiting in the Test


The assertion at line 5 in the ServerTest listing calls the waitForResults method, which will suspend execution of the current thread (i.e., the thread in which the test is executing) until all search results have been retrieved. The timeout value provides an arbitrary elapsed time after which waitForResults should return false and cause the assertion to fail.

 private boolean waitForResults() {    long start = System.currentTimeMillis();    while (numberOfResults < URLS.length) {       try {Thread.sleep(1); }       catch (InterruptedException e) {}       if (System.currentTimeMillis() - start > TIMEOUT)          return false;    }    return true; } 

The waitForResults method executes a simple loop. Each time through, the body of the loop pauses for a millisecond, then makes a quick calculation of elapsed time to see if it's passed the timeout limit. The pause is effected by a call to the static Thread method sleep. The sleep method takes a number of milliseconds and idles the currently executing thread for that amount of time.[4]

[4] The thread scheduler will wait at least the specified amount of time and possibly a bit longer.

Since sleep can throw a checked exception of type InterruptedException, you can choose to enclose it in a try-catch block. It is possible for one thread to interrupt another, which is what would generate the exception. But thread interruptions are usually only by design, so the code here shows one of the rare cases where it's acceptable to ignore the exception and provide an empty catch block.

The looping mechanism used in waitForResults is adequate at best. The wait/notify technique, discussed later in this lesson (see Wait/Notify), provides the best general-purpose mechanism of waiting for a condition to occur.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net