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:

  1. <dependency>
  2. <groupId>junit</groupId>
  3. <artifactId>junit</artifactId>
  4. <version>4.12</version>
  5. <scope>test</scope>
  6. </dependency>
  7. <dependency>
  8. <groupId>io.vertx</groupId>
  9. <artifactId>vertx-unit</artifactId>
  10. <scope>test</scope>
  11. </dependency>

JUnit tests need to be annotated with the VertxUnitRunner runner to use the vertx-unit features:

  1. @RunWith(VertxUnitRunner.class)
  2. public class SomeTest {
  3. // (...)
  4. }

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:

  1. @Test /*(timeout=5000)*/ (8)
  2. public void async_behavior(TestContext context) { (1)
  3. Vertx vertx = Vertx.vertx(); (2)
  4. context.assertEquals("foo", "foo"); (3)
  5. Async a1 = context.async(); (4)
  6. Async a2 = context.async(3); (5)
  7. vertx.setTimer(100, n -> a1.complete()); (6)
  8. vertx.setPeriodic(100, n -> a2.countDown()); (7)
  9. }
  1. TestContext is a parameter provided by the runner.

  2. Since we are in unit tests, we need to create a Vert.x context.

  3. Here is an example of a basic TestContext assertion.

  4. We get a first Async object that can later be completed (or failed).

  5. This Async object works as a countdown that completes successfully after 3 calls.

  6. We complete when the timer fires.

  7. Each periodic task tick triggers a countdown. The test passes when all Async objects have completed.

  8. There is a default (long) timeout for asynchronous test cases, but it can be overridden through the JUnit @Test annotation.