I have implemented one Verticle as mentioned below. Verticle is working as expected. Now I am trying to write Junit test case for this Verticle which could test the start method, the handler method handleRequest(), and the method getSomeData() inside handler which returns Future. Either single test case to test all three method or individual test case to test individual method should be fine. I know writing Junit test cases for synchronous code but have no idea how exactly to write Junit TCs for Verticle in vert.x which is asynchronous. Could anyone please guide me here? I also have router verticle from which I am sending message to this consumer verticle MyVerticle but I am thinking to write Jnuit test cases for this consumer verticle first. Please help.
@Component
public class MyVerticle extends AbstractVerticle{
@Override
public void start() throws Exception {
super.start();
vertx.eventBus().<String>consumer("address.xyz").handler(handleRequest());
}
private Handler<Message<String>> handleRequest() {
return msg -> {
getSomeData(msg.body().toString())
.setHandler(ar -> {
if(ar.succeeded()){
msg.reply(ar.result());
}else{
msg.reply(ar.cause().getMessage());
}
});
};
}
private Future<String> getSomeData(String inputJson) {
Promise<String> promise = Promise.promise();
promise.complete("Returning Data");
return promise.future();
}
}
I recommend using the vertx-unit project, wich makes it easy to test async code. For your parcular case it would go like this:
import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(VertxUnitRunner.class)
public class MainVerticleTest {
private Vertx vertx;
@Before
public void setup(TestContext ctx){
Async async = ctx.async();
this.vertx = Vertx.vertx();
vertx.deployVerticle(MyVerticle.class.getName(), h -> {
if(h.succeeded()){
async.complete();
}else{
ctx.fail();
}
});
}
@Test
public void test_consumption(TestContext ctx) {
Async async = ctx.async();
vertx.eventBus().request("address.xyz","message", h ->{
if(h.succeeded()){
ctx.assertEquals("Returning Data",h.result().body().toString());
async.complete();
}else{
ctx.fail(h.cause());
}
});
}
}