Home | History | Annotate | Download | only in testing
      1 /*
      2  * Copyright (C) 2010 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.i18n.addressinput.testing;
     18 
     19 import junit.framework.TestCase;
     20 
     21 import java.util.concurrent.TimeoutException;
     22 
     23 /**
     24  * An extension of TestCase that provides delayTestFinish() and finishTest() methods that behave
     25  * like the corresponding methods in GWTTestCase for testing asynchronous code.
     26  */
     27 public abstract class AsyncTestCase extends TestCase {
     28     /**
     29      * Tracks whether this test is completely done.
     30      */
     31     private boolean mTestIsFinished;
     32 
     33     /**
     34      * The system time in milliseconds when the test should time out.
     35      */
     36     private long mTestTimeoutMillis;
     37 
     38     /**
     39      * Puts the current test in asynchronous mode.
     40      *
     41      * @param timeoutMillis time to wait before failing the test for timing out
     42      */
     43     protected void delayTestFinish(int timeoutMillis) {
     44         mTestTimeoutMillis = System.currentTimeMillis() + timeoutMillis;
     45     }
     46 
     47     /**
     48      * Causes this test to succeed during asynchronous mode.
     49      */
     50     protected void finishTest() {
     51         mTestIsFinished = true;
     52         synchronized (this) {
     53             notify();
     54         }
     55     }
     56 
     57     @Override
     58     protected void runTest() throws Throwable {
     59         mTestIsFinished = false;
     60         mTestTimeoutMillis = 0;
     61         super.runTest();
     62 
     63         if (mTestTimeoutMillis > 0) {
     64             long timeoutMillis = mTestTimeoutMillis - System.currentTimeMillis();
     65             if (timeoutMillis > 0) {
     66                 synchronized (this) {
     67                     wait(timeoutMillis);
     68                 }
     69             }
     70             if (!mTestIsFinished) {
     71                 throw new TimeoutException("Waited " + timeoutMillis + " ms!");
     72             }
     73         }
     74     }
     75 }
     76