I have :
Router.router(vertx).route().handler(new Handler<RoutingContext>() {
@Override
public void handle(RoutingContext event) {
HttpServerRequest request = event.request();
Buffer body = event.getBody();
HttpServerResponse response = event.response();
// Some code to test
response.setStatusCode(200);
response.end();
}
});
How to unit test this by giving prepared request and body, and by inspecting the response ?
Usually testing such end points is more an integration-test rather than a unit test. No need to mock everything. mocking is meant for testing some external services which is not available at your test context. here is a sample to do an integration test with vert.x :
@ExtendWith(VertxExtension.class)
class IntegrationTest {
private static RequestSpecification requestSpecification;
@BeforeAll
static void prepareSpec() {
requestSpecification = new RequestSpecBuilder()
.addFilters(asList(new ResponseLoggingFilter(), new RequestLoggingFilter()))
.setBaseUri("http://localhost:3002/")// Depends on your verticle config.
.build();
}
@BeforeEach
void setup(Vertx vertx, VertxTestContext testContext) {
vertx
.deployVerticle(new MyVerticle(),
ar -> {
if(ar.succeeded()) {
testContext.completeNow();
} else {
testContext.failNow(ar.cause());
}
}
);
}
@Test
@DisplayName("Test message")
void test() {
JsonObject body = new JsonObject();//Fill it as you want
given(requestSpecification)
.contentType(ContentType.JSON)
.body(body.encode())
.post("/yourreqest")//Your resource path
.then()
.assertThat()
.statusCode(200);//expected status
}
The unit to be tested here is your implementation of Handler
.
So change the anonymous class to (at least) a (non private
) static
inner class .
class MyHandler implements Handler<RoutingContext> {
@Override
public void handle(RoutingContext event) {
HttpServerRequest request = event.request();
Buffer body = event.getBody();
HttpServerResponse response = event.response();
// Some code to test
response.setStatusCode(200);
response.end();
}
};
Router.router(vertx).route().handler(new MyHandler());
Then you can create an instance of your Handlre for testing an pass in a mock as context
returning mocks for request
and response
.
@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
class MyHandlerTest {
@Mock
RoutingContext event;
@Mock
HttpServerRequest request;
@Mock
HttpServerResponse response;
@BeforeEach
public void setup(){
doReturn(request).when(event).getRequest();
doReturn(response).when(event)event.response();
}
@Test
public void shouldSetStatusTo200whenNoError(){
// arrange
doReturn(SOME_VALID_BODY).when(request).getBody();
// act
new MyHandler().handle(event);
// assert
Mockito.verify(response).setStatusCode(200);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.