我有一个junit测试,我想建立一个聚集的vert.x环境。如果我从setUp
方法运行public static void main()
方法中的代码,但是如果它是从setUp
方法运行,则它可以正常工作。
永远不会调用public void handle(AsyncResult<Vertx> res)
方法!
为什么呢?
@RunWith(VertxUnitRunner.class)
public class TestMyStuff {
private Vertx vertx;
@Before
public void setUp(TestContext context) throws IOException {
ClusterManager mgr = new HazelcastClusterManager();
VertxOptions options = new VertxOptions().setClusterManager(mgr);
Vertx.clusteredVertx(options, new Handler<AsyncResult<Vertx>>() {
@Override
public void handle(AsyncResult<Vertx> res) {
if(res.succeeded()) {
vertx = res.result();
DeploymentOptions options = new DeploymentOptions()
.setConfig(new JsonObject().put("http.port", 8080)
);
vertx.deployVerticle(MyWebService.class.getName(), options, context.asyncAssertSuccess());
System.out.println("SUCCESS");
} else {
System.out.println("FAILED");
}
}
});
}
@Test
public void printSomething(TestContext context) {
System.out.println("Print from method printSomething()");
}
&#34; Print from method printSomething()
&#34;是写作但不是#34; SUCCESS
&#34;或&#34; FAILED
&#34;来自handle()方法。
为什么它不能在setUp方法中起作用,而是从main()?
起作用答案 0 :(得分:2)
由于VertX的异步行为,测试未正确设置:
前段时间我也遇到过这个问题,所以在这种情况下应该怎么做?
您应该正确设置VertX并等待测试方法完成设置。我可以使用等待机制,使用Awaitility(https://github.com/jayway/awaitility)完成此任务。
要点
我
@RunWith(VertxUnitRunner.class)
public class TestMyStuff {
private Vertx vertx;
final AtomicBoolean loaded = new AtomicBoolean(false);
@Before
public void setUp(TestContext context) throws IOException {
ClusterManager mgr = new HazelcastClusterManager();
VertxOptions options = new VertxOptions().setClusterManager(mgr);
Vertx.clusteredVertx(options, new Handler<AsyncResult<Vertx>>() {
@Override
public void handle(AsyncResult<Vertx> res) {
if (res.succeeded()) {
vertx = res.result();
DeploymentOptions options = new DeploymentOptions()
.setConfig(new JsonObject().put("http.port", 8080)
);
//vertx.deployVerticle(MyWebService.class.getName(), options, context.asyncAssertSuccess());
System.out.println("SUCCESS");
loaded.set(true);
} else {
System.out.println("FAILED");
}
}
});
}
@Test
public void printSomething(TestContext context) {
Awaitility.waitAtMost(Duration.ONE_MINUTE).await().untilTrue(loaded);
System.out.println("Print from method printSomething()");
}
}
我希望这有助于理解要点,因此您也可以找到其他任何解决方法!
答案 1 :(得分:1)
VertX确实有自己的函数来处理多线程和异步请求。
只需在Test函数中使用Async类:
@Test
public void printSomething(TestContext context) {
Async async = context.async();
System.out.println("Print from method printSomething()");
async.complete();
}
希望将来有所帮助。