当前位置:网站首页>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
边栏推荐
- Distributed transactions
- Leetcode 213: 打家劫舍 II
- Lombok cooperates with @slf4j and logback to realize logging
- 你开发数据API最快多长时间?我1分钟就足够了
- Wireshark software usage
- Dora (discover offer request recognition) process of obtaining IP address
- Circuit, packet and message exchange
- Leetcode 198: 打家劫舍
- [cmake] cmake link SQLite Library
- Advanced API (character stream & net for beginners)
猜你喜欢

深度学习参数初始化(一)Xavier初始化 含代码

TreeMap

《指环王:力量之戒》新剧照 力量之戒铸造者亮相

Use of generics

Homology policy / cross domain and cross domain solutions /web security attacks CSRF and XSS
![[solved] sqlexception: invalid value for getint() - 'Tian Peng‘](/img/bf/f6310304d58d964b3d09a9d011ddb5.png)
[solved] sqlexception: invalid value for getint() - 'Tian Peng‘

Comparison of advantages and disadvantages between most complete SQL and NoSQL

Recursion, Fibonacci sequence

Interview questions about producers and consumers (important)

Basic knowledge about SQL database
随机推荐
twenty million two hundred and twenty thousand three hundred and nineteen
C代码生产YUV420 planar格式文件
Various postures of CS without online line
【已解决】win10找不到本地组策略编辑器解决方法
Jeecg menu path display problem
4279. Cartesian tree
The education of a value investor
Use of generics
4279. 笛卡尔树
II. D3.js draw a simple figure -- circle
Selenium key knowledge explanation
Book recommendation~
最全SQL与NoSQL优缺点对比
Specified interval inversion in the linked list
OSI knowledge sorting
Advanced API (multithreading 02)
Sorting, dichotomy
【CMake】CMake链接SQLite库
[untitled]
The difference between typescript let and VaR