Testing database operations
The database service is a good fit for writing tests.
We first need to deploy the database verticle. We will configure the JDBC connection to be HSQLDB with an in-memory storage, and upon success we will fetch a service proxy for our test cases.
Since these operations are involving, we leverage the JUnit before / after life-cycle methods:
private Vertx vertx;
private WikiDatabaseService service;
@Before
public void prepare(TestContext context) throws InterruptedException {
vertx = Vertx.vertx();
JsonObject conf = new JsonObject() (1)
.put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_URL, "jdbc:hsqldb:mem:testdb;shutdown=true")
.put(WikiDatabaseVerticle.CONFIG_WIKIDB_JDBC_MAX_POOL_SIZE, 4);
vertx.deployVerticle(new WikiDatabaseVerticle(), new DeploymentOptions().setConfig(conf),
context.asyncAssertSuccess(id -> (2)
service = WikiDatabaseService.createProxy(vertx, WikiDatabaseVerticle.CONFIG_WIKIDB_QUEUE)));
}
We only override some of the verticle settings, the others will have default values.
asyncAssertSuccess
is useful to provide a handler that checks for the success of an asynchronous operation. There is a variant with no arguments, and a variant like this one where we can chain the result to another handler.
Cleaning up the Vert.x context is straightforward, and again we use asyncAssertSuccess
to ensure that no error was encountered:
@After
public void finish(TestContext context) {
vertx.close(context.asyncAssertSuccess());
}
The service operations are essentially CRUD operations, so a JUnit test case combining all of them is a fine way to test:
@Test
public void crud_operations(TestContext context) {
Async async = context.async();
service.createPage("Test", "Some content", context.asyncAssertSuccess(v1 -> {
service.fetchPage("Test", context.asyncAssertSuccess(json1 -> {
context.assertTrue(json1.getBoolean("found"));
context.assertTrue(json1.containsKey("id"));
context.assertEquals("Some content", json1.getString("rawContent"));
service.savePage(json1.getInteger("id"), "Yo!", context.asyncAssertSuccess(v2 -> {
service.fetchAllPages(context.asyncAssertSuccess(array1 -> {
context.assertEquals(1, array1.size());
service.fetchPage("Test", context.asyncAssertSuccess(json2 -> {
context.assertEquals("Yo!", json2.getString("rawContent"));
service.deletePage(json1.getInteger("id"), v3 -> {
service.fetchAllPages(context.asyncAssertSuccess(array2 -> {
context.assertTrue(array2.isEmpty());
async.complete(); (1)
}));
});
}));
}));
}));
}));
}));
async.awaitSuccess(5000); (2)
}
This is where the sole
Async
eventually completes.This is an alternative to exiting the test case method and relying on a JUnit timeout. Here the execution on the test case thread waits until either the
Async
completes or the timeout period elapses.