Getting started
The vertx-unit
module provides utilities to test asynchronous operations in Vert.x. Aside from that, you can use your testing framework of choice like JUnit.
With JUnit, the required Maven dependencies are the following:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-unit</artifactId>
<scope>test</scope>
</dependency>
JUnit tests need to be annotated with the VertxUnitRunner
runner to use the vertx-unit
features:
@RunWith(VertxUnitRunner.class)
public class SomeTest {
// (...)
}
With that runner, JUnit test and life-cycle methods accept a TestContext
argument. This object provides access to basic assertions, a context to store data, and several async-oriented helpers that we will see in this section.
To illustrate that, let us consider an asynchronous scenario where we want to check that a timer task has been called once, and that a periodic task has been called 3 times. Since that code is asynchronous, the test method exits before the test completes, so making that test pass or fail also needs to be done in an asynchronous fashion:
@Test /*(timeout=5000)*/ (8)
public void async_behavior(TestContext context) { (1)
Vertx vertx = Vertx.vertx(); (2)
context.assertEquals("foo", "foo"); (3)
Async a1 = context.async(); (4)
Async a2 = context.async(3); (5)
vertx.setTimer(100, n -> a1.complete()); (6)
vertx.setPeriodic(100, n -> a2.countDown()); (7)
}
TestContext
is a parameter provided by the runner.Since we are in unit tests, we need to create a Vert.x context.
Here is an example of a basic
TestContext
assertion.We get a first
Async
object that can later be completed (or failed).This
Async
object works as a countdown that completes successfully after 3 calls.We complete when the timer fires.
Each periodic task tick triggers a countdown. The test passes when all
Async
objects have completed.There is a default (long) timeout for asynchronous test cases, but it can be overridden through the JUnit
@Test
annotation.