当前位置:网站首页>JUnit unit test of vertx
JUnit unit test of vertx
2022-07-03 07:25:00 【Sleeping Empire】
Introduce
Vertx-junit5 This module is for use JUnit 5 To write Vert.x Testing provides integration and support
1. maven Project dependence
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-config-yaml</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.lance.common</groupId>
<artifactId>vertx-common-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-junit5</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.YAML File configuration
server:
port: 18002
3. Start loading profile , And into the config In the middle
public class UnitApplication {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
ConfigRetriever retriever = readYaml(vertx);
retriever.getConfig(json -> {
DeploymentOptions options = new DeploymentOptions().setConfig(json.result());
vertx.deployVerticle(MainApp.class.getName(), options);
});
}
private static ConfigRetriever readYaml(Vertx vertx) {
ConfigStoreOptions store = new ConfigStoreOptions()
.setType("file")
.setFormat("yaml")
.setOptional(true)
.setConfig(new JsonObject().put("path", "application.yaml"));
return ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(store));
}
}
4.Vertx http client unit testing
Slf4j
@ExtendWith(VertxExtension.class)
class WebRequestTests {
private final Vertx vertx = Vertx.vertx();
/**
* test vertx server
*/
@Test
@Disabled
void suite() {
vertx.createHttpServer()
.requestHandler(req -> req.response().end("Ok"))
.listen(16969, ar -> {
log.info("===> vertx start: {}", ar.succeeded());
});
}
/**
* 1. Allow waiting for operations in other threads to notify completion , similar java in promise object
* 2. Support to receive assertion failures to mark tests as failures
*/
@Test
@Disabled
void asyncContext() throws Throwable {
VertxTestContext testContext = new VertxTestContext();
vertx.createHttpServer()
.requestHandler(req -> req.response().end())
.listen(16969)
.onComplete(testContext.succeedingThenComplete());
//.onComplete(testContext.failingThenComplete());
Assertions.assertTrue(testContext.awaitCompletion(5, TimeUnit.SECONDS));
if (testContext.failed()) {
throw testContext.causeOfFailure();
}
}
/**
* Test http client
*/
@Test
@Disabled
void httpClient() throws Exception {
HttpClient client = vertx.createHttpClient();
VertxTestContext testContext = new VertxTestContext();
client.request(HttpMethod.GET, 18002, "127.0.0.1", "/user/info/2")
.compose(req -> req.send().compose(HttpClientResponse::body))
.onComplete(testContext.succeeding(buffer -> testContext.verify(() -> {
JsonObject jsonObject = buffer.toJsonObject();
log.info("===>Response body: {}", jsonObject);
Assertions.assertEquals(jsonObject.getString("code"), HttpResponseStatus.OK.reasonPhrase());
testContext.completeNow();
}))).onFailure(event -> log.error("===>fail: ", event.getCause()));
boolean awaitResult = testContext.awaitCompletion(30, TimeUnit.SECONDS);
log.info("===>Await: {}", awaitResult);
}
/**
* Many tests can be marked as passed by simply calling completeNow At a certain point in time of execution . That being the case , in many instances , The success of the test depends on the different asynchronous parts to be verified .
*/
@Test
@Disabled
void checkpoint() {
int port = 9001;
VertxTestContext testContext = new VertxTestContext();
Checkpoint serverStarted = testContext.checkpoint();
Checkpoint requestsServed = testContext.checkpoint(10);
Checkpoint responsesReceived = testContext.checkpoint(10);
vertx.createHttpServer()
.requestHandler(req -> {
req.response().end("success");
requestsServed.flag();
})
.listen(port)
.onComplete(testContext.succeeding(httpServer -> {
serverStarted.flag();
HttpClient client = vertx.createHttpClient();
for (int i = 0; i < 10; i++) {
client.request(HttpMethod.GET, port, "localhost", "/")
.compose(req -> req.send().compose(HttpClientResponse::body))
.onComplete(testContext.succeeding(buffer -> testContext.verify(() -> {
Assertions.assertEquals("success", buffer.toString());
responsesReceived.flag();
}))
);
}
})
);
}
}
5.Vertx test context unit testing
@Slf4j
@ExtendWith(VertxExtension.class)
class VertxExtensionTests {
private final int port = 9000;
@BeforeEach
void init(Vertx vertx, VertxTestContext testContext) {
vertx.deployVerticle(new HttpServerVertical(), testContext.succeedingThenComplete());
}
@AfterEach
public void after(Vertx vertx) {
log.info("===>Vertx close.");
vertx.close();
}
/**
* Continuous test 3 Time
* repetition 1 of 3
* repetition 2 of 3
* repetition 3 of 3
*/
@Disabled
@RepeatedTest(3)
void request3Times(Vertx vertx, VertxTestContext testContext) {
HttpClient client = vertx.createHttpClient();
client.request(HttpMethod.GET, port, "localhost", "/")
.compose(req -> req.send().compose(HttpClientResponse::body))
.onComplete(testContext.succeeding(buffer -> testContext.verify(() -> {
log.info("===>Response result: {}", buffer.toString());
testContext.completeNow();
})));
}
@Test
@Timeout(value = 100, unit = TimeUnit.MILLISECONDS)
void timeout(Vertx vertx, VertxTestContext testContext) {
HttpClient client = vertx.createHttpClient();
client.request(HttpMethod.GET, port, "localhost", "/")
.compose(req -> req.send().compose(HttpClientResponse::body))
.onComplete(testContext.succeeding(buffer -> testContext.verify(() -> {
Thread.sleep(5000L);
log.info("===>Response timeout result: {}", buffer.toString());
testContext.completeNow();
})));
}
/**
* Single service test
*/
@Test
@Disabled
void httpServerResponse(Vertx vertx, VertxTestContext testContext) {
vertx.deployVerticle(new HttpServerVertical(), testContext.succeeding(id -> {
HttpClient client = vertx.createHttpClient();
client.request(HttpMethod.GET, port, "localhost", "/")
.compose(req -> req.send().compose(HttpClientResponse::body))
.onComplete(testContext.succeeding(buffer -> testContext.verify(() -> {
log.info("===>Response result: {}", buffer.toString());
Assertions.assertEquals(buffer.toString(), "success");
testContext.completeNow();
})));
}));
}
class HttpServerVertical extends AbstractVerticle {
@Override
public void start() throws Exception {
vertx.createHttpServer()
.requestHandler(req -> {
req.response().end("success");
})
.listen(port).onComplete(event -> {
if (event.succeeded()) {
log.info("===>Start [{}] success!", port);
return;
}
log.error("===>Start fail: ", event.cause());
});
}
}
}
6. Full address of the project
边栏推荐
- 【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
- Qtip2 solves the problem of too many texts
- LeetCode
- Introduction of transformation flow
- 【CoppeliaSim4.3】C#调用 remoteApi控制场景中UR5
- Interview questions about producers and consumers (important)
- Longest common prefix and
- c语言指针的概念
- VMWare网络模式-桥接,Host-Only,NAT网络
- [set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)
猜你喜欢
带你全流程,全方位的了解属于测试的软件事故
论文学习——鄱阳湖星子站水位时间序列相似度研究
Dora (discover offer request recognition) process of obtaining IP address
Basic knowledge about SQL database
1. E-commerce tool cefsharp autojs MySQL Alibaba cloud react C RPA automated script, open source log
Various postures of CS without online line
docker建立mysql:5.7版本指定路径挂载不上。
Specified interval inversion in the linked list
IP home online query platform
[solved] sqlexception: invalid value for getint() - 'Tian Peng‘
随机推荐
【无标题】
New stills of Lord of the rings: the ring of strength: the caster of the ring of strength appears
Recursion, Fibonacci sequence
3311. 最长算术
【已解决】Unknown error 1146
Spa single page application
Industrial resilience
Specified interval inversion in the linked list
Warehouse database fields_ Summary of SQL problems in kingbase8 migration of Jincang database
Some experiences of Arduino soft serial port communication
High concurrency memory pool
Advanced API (local simulation download file)
Docker builds MySQL: the specified path of version 5.7 cannot be mounted.
Common architectures of IO streams
Longest common prefix and
IPv4 address
[most detailed] latest and complete redis interview book (50)
Basic knowledge about SQL database
深度学习参数初始化(一)Xavier初始化 含代码
带你全流程,全方位的了解属于测试的软件事故