Here's how to write simple unit tests for Vert.x applications using just JUnit (which comes with Vert.x) without additional testing frameworks:
Basic Setup
First, add the Vert.x JUnit 5 dependency to your project:
xml
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-junit5</artifactId>
<scope>test</scope>
</dependency>
Simple Verticle Test
Here's a basic example testing a verticle:
java
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(VertxExtension.class)
public class MyVerticleTest {
@Test
public void testVerticleDeployment(Vertx vertx, VertxTestContext testContext) {
vertx.deployVerticle(new MyVerticle(), testContext.succeeding(id -> testContext.completeNow()));
}
}
class MyVerticle extends AbstractVerticle {
@Override
public void start() {
vertx.eventBus().consumer("test.address", message -> {
message.reply("pong");
});
}
}
Testing Async Operations
For testing asynchronous operations:
java
@Test
public void testAsyncOperation(Vertx vertx, VertxTestContext testContext) {
vertx.setTimer(100, id -> {
testContext.verify(() -> {
// Your assertions here
assertTrue(true);
});
testContext.completeNow();
});
}
Testing HTTP Endpoints
Testing an HTTP server without additional frameworks:
java
@Test
public void testHttpServer(Vertx vertx, VertxTestContext testContext) {
vertx.createHttpServer()
.requestHandler(req -> req.response().end("Hello"))
.listen(8080, testContext.succeeding(server -> {
vertx.createHttpClient()
.request(HttpMethod.GET, 8080, "localhost", "/")
.compose(req -> req.send())
.compose(resp -> resp.body())
.onSuccess(body -> {
testContext.verify(() -> {
assertEquals("Hello", body.toString());
});
testContext.completeNow();
});
}));
}
Testing Event Bus
Testing event bus communication:
java
@Test
public void testEventBus(Vertx vertx, VertxTestContext testContext) {
vertx.eventBus().consumer("test.address", message -> {
assertEquals("ping", message.body());
message.reply("pong");
});
vertx.eventBus().request("test.address", "ping", reply -> {
testContext.verify(() -> {
assertTrue(reply.succeeded());
assertEquals("pong", reply.result().body());
});
testContext.completeNow();
});
}
Key Points
- Use
VertxTestContext to handle async completion with completeNow() or failNow()
- Use
testContext.succeeding() and testContext.failing() for handling async results
- Call
testContext.verify() to wrap assertions in async handlers
- The test will timeout (default 30 seconds) if
completeNow() isn't called
This approach uses only JUnit 5 and the built-in Vert.x testing utilities without any additional testing frameworks.