当前位置:网站首页>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
边栏推荐
- [set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)
- How long is the fastest time you can develop data API? One minute is enough for me
- Industrial resilience
- Advanced APL (realize group chat room)
- "Moss ma not found" solution
- Introduction of buffer flow
- C WinForm framework
- Sorting, dichotomy
- Chrome 98 Private Network Access problem w/ disabled web security: Request had no target IP address
- Lombok -- simplify code
猜你喜欢

Leetcode 198: 打家劫舍

Discussion on some problems of array

【已解决】Unknown error 1146

Basic components and intermediate components

Le Seigneur des anneaux: l'anneau du pouvoir

Final, override, polymorphism, abstraction, interface

Interfaces and related concepts

How long is the fastest time you can develop data API? One minute is enough for me

Common problems in io streams
![[HCAI] learning summary OSI model](/img/90/66505b22e32aa00b26886a9d5c5e4c.jpg)
[HCAI] learning summary OSI model
随机推荐
IP home online query platform
4279. 笛卡尔树
你开发数据API最快多长时间?我1分钟就足够了
docket
Advanced API (byte stream & buffer stream)
VMware virtual machine installation
为什么说数据服务化是下一代数据中台的方向?
【CoppeliaSim4.3】C#调用 remoteApi控制场景中UR5
Arduino Serial系列函数 有关print read 的总结
GStreamer ffmpeg avdec decoded data flow analysis
Pat grade a real problem 1166
10 000 volumes - Guide de l'investisseur en valeur [l'éducation d'un investisseur en valeur]
[set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)
Hisat2 - stringtie - deseq2 pipeline for bulk RNA seq
Store WordPress media content on 4everland to complete decentralized storage
Longest common prefix and
Chrome 98 Private Network Access problem w/ disabled web security: Request had no target IP address
The education of a value investor
Summary of Arduino serial functions related to print read
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef