|
| 1 | +package io.vertx.example.unit.test; |
| 2 | + |
| 3 | +import io.vertx.core.DeploymentOptions; |
| 4 | +import io.vertx.core.Vertx; |
| 5 | +import io.vertx.core.http.HttpClient; |
| 6 | +import io.vertx.core.json.JsonObject; |
| 7 | +import io.vertx.example.unit.HelloVerticle; |
| 8 | +import io.vertx.ext.unit.Async; |
| 9 | +import io.vertx.ext.unit.TestContext; |
| 10 | +import io.vertx.ext.unit.junit.VertxUnitRunner; |
| 11 | + |
| 12 | +import java.io.IOException; |
| 13 | +import java.net.ServerSocket; |
| 14 | + |
| 15 | +import org.junit.After; |
| 16 | +import org.junit.Before; |
| 17 | +import org.junit.Test; |
| 18 | +import org.junit.runner.RunWith; |
| 19 | + |
| 20 | +/* |
| 21 | + * Example of an asynchronous JUnit test for a Verticle. |
| 22 | + */ |
| 23 | +@RunWith(VertxUnitRunner.class) |
| 24 | +public class JUnitVerticleTest { |
| 25 | + |
| 26 | + Vertx vertx; |
| 27 | + int port; |
| 28 | + |
| 29 | + @Before |
| 30 | + public void before(TestContext context) throws IOException { |
| 31 | + ServerSocket socket = new ServerSocket(0); |
| 32 | + port = socket.getLocalPort(); |
| 33 | + socket.close(); |
| 34 | + |
| 35 | + DeploymentOptions options = new DeploymentOptions() |
| 36 | + .setConfig(new JsonObject().put("http.port", port)); |
| 37 | + |
| 38 | + vertx = Vertx.vertx(); |
| 39 | + vertx.deployVerticle(HelloVerticle.class.getName(), options, context.asyncAssertSuccess()); |
| 40 | + } |
| 41 | + |
| 42 | + @After |
| 43 | + public void after(TestContext context) { |
| 44 | + vertx.close(context.asyncAssertSuccess()); |
| 45 | + } |
| 46 | + |
| 47 | + @Test |
| 48 | + public void canGetHello(TestContext context) { |
| 49 | + Async async = context.async(); |
| 50 | + HttpClient client = vertx.createHttpClient(); |
| 51 | + client.getNow(port, "localhost", "/", response -> { |
| 52 | + response.bodyHandler(body -> { |
| 53 | + context.assertEquals("Hello!", body.toString()); |
| 54 | + client.close(); |
| 55 | + async.complete(); |
| 56 | + }); |
| 57 | + }); |
| 58 | + } |
| 59 | +} |
0 commit comments