Skip to content

Instantly share code, notes, and snippets.

@silmeth
Created May 27, 2019 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silmeth/d60c239b550199c3a6a8c48fdbe75817 to your computer and use it in GitHub Desktop.
Save silmeth/d60c239b550199c3a6a8c48fdbe75817 to your computer and use it in GitHub Desktop.
How to test some logic depending on Vertx context, returning a VertxCompletableFuture, using Junit Jupiter API
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import io.vertx.core.Vertx;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import pl.omnilogy.utils.vertx.VertxCompletableFuture;
import static org.junit.jupiter.api.Assertions.assertTrue;
class VertxCompletableFutureJupiterTest {
private Vertx vertx;
@BeforeEach
void setUpVertx() {
vertx = Vertx.vertx();
}
@Test
void testSomething() {
boolean result = runOnVertxContext(() -> {
// here test Vertx functions
return VertxCompletableFuture.supplyBlockingAsync(() -> true);
}).join();
assertTrue(result);
}
@AfterEach
void destroyVertx() {
CompletableFuture<Void> vertxClosed = new CompletableFuture<>();
vertx.close(res -> {
if (res.succeeded()) {
vertxClosed.complete(null);
} else {
vertxClosed.completeExceptionally(res.cause());
}
});
vertxClosed.join();
}
private <T> CompletableFuture<T> runOnVertxContext(Supplier<CompletableFuture<T>> supplier) {
CompletableFuture<T> result = new CompletableFuture<>();
vertx.runOnContext(v -> {
supplier.get()
.thenAcceptAsync(result::complete)
.exceptionally(e -> {
result.completeExceptionally(e);
return null;
});
});
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment