当前位置:网站首页>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
边栏推荐
- Hash table, generic
- 专题 | 同步 异步
- 4279. Cartesian tree
- c语言指针的概念
- Advanced API (serialization & deserialization)
- SQL create temporary table
- twenty million two hundred and twenty thousand three hundred and nineteen
- Arduino 软串口通信 的几点体会
- Map interface and method
- Visit Google homepage to display this page, which cannot be displayed
猜你喜欢
4279. Cartesian tree
Use of other streams
Docker builds MySQL: the specified path of version 5.7 cannot be mounted.
Introduction of transformation flow
Custom generic structure
The embodiment of generics in inheritance and wildcards
PAT甲级真题1166
Margin left: -100% understanding in the Grail layout
C代码生产YUV420 planar格式文件
Common problems in io streams
随机推荐
SharePoint modification usage analysis report is more than 30 days
7.2 brush two questions
Selenium key knowledge explanation
为什么说数据服务化是下一代数据中台的方向?
Circuit, packet and message exchange
【已解决】SQLException: Invalid value for getInt() - ‘田鹏‘
Wireshark software usage
Advanced API (local simulation download file)
3311. Longest arithmetic
JS monitors empty objects and empty references
Arduino Serial系列函数 有关print read 的总结
Win 2008 R2 crashed at the final installation stage
Visit Google homepage to display this page, which cannot be displayed
Distributed lock
1. E-commerce tool cefsharp autojs MySQL Alibaba cloud react C RPA automated script, open source log
OSI knowledge sorting
20220319
Raspberry pie update tool chain
[solved] win10 cannot find a solution to the local group policy editor
Jeecg data button permission settings