Created
December 20, 2012 13:07
-
-
Save darylteo/4345225 to your computer and use it in GitHub Desktop.
Testing asynchronous code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.BeforeClass; | |
import org.junit.Test; | |
import org.vertx.java.core.Handler; | |
import org.vertx.java.core.Vertx; | |
import org.vertx.java.deploy.impl.VertxLocator; | |
public class PromiseTests { | |
private Object lock = new Object(); | |
@BeforeClass | |
public static void environment() { | |
VertxLocator.vertx = Vertx.newVertx(); | |
} | |
public Promise<Object> makePromise() { | |
final Promise<Object> promise = new Promise<>(); | |
VertxLocator.vertx.runOnLoop(new Handler<Void>() { | |
@Override | |
public void handle(Void event) { | |
System.out.print("Working."); | |
for (int i = 0; i < 10; i++) { | |
System.out.print("."); | |
try { | |
Thread.sleep(200); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
System.out.println(); | |
promise.fulfill("Hello World"); | |
} | |
}); | |
return promise; | |
} | |
@Test | |
public void basic() throws Exception { | |
runTest(new Runnable() { | |
@Override | |
public void run() { | |
makePromise() | |
.then(new PromiseHandler<Void>() { | |
@Override | |
public Void handle() { | |
System.out.println("Wish granted"); | |
endTest(); | |
return null; | |
} | |
}); | |
} | |
}); | |
} | |
@Test | |
public void chain() throws Exception { | |
runTest(new Runnable() { | |
@Override | |
public void run() { | |
makePromise() | |
.then(new PromiseHandler<Void>() { | |
@Override | |
public Void handle() { | |
System.out.println("Wish granted"); | |
return null; | |
} | |
}) | |
.then(new PromiseHandler<Void>() { | |
@Override | |
public Void handle() { | |
System.out.println("What shall I do with my wish?"); | |
endTest(); | |
return null; | |
} | |
}); | |
} | |
}); | |
} | |
private void waitTest() throws InterruptedException { | |
synchronized (lock) { | |
lock.wait(); | |
} | |
} | |
private void endTest() { | |
synchronized (lock) { | |
lock.notifyAll(); | |
} | |
} | |
private void runTest(Runnable runnable) throws InterruptedException { | |
new Thread(runnable).start(); | |
waitTest(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment