I am having below kind of EntityRouter, now my question is without autowired handler, how can i mock and write junit unit-tests (not-integration) for such endpoint?
Note: with controller, it is simple for me concept wise, as i can mock service which is usually autowired in controller if we are using spring-web-mvc.
public class EntityRouter {
@Bean
public RouterFunction<ServerResponse> route(EntityHandler handler) {
return RouterFunctions
.route(GET("/getAllEntities").and(accept(MediaType.APPLICATION_JSON)), handler::findAll)
.andRoute(GET("/getEntity/{id}").and(accept(MediaType.APPLICATION_STREAM_JSON)), handler::findById)
.andRoute(POST("/createEntity").and(accept(MediaType.APPLICATION_JSON)), handler::save)
.andRoute(DELETE("/deleteEntity/{id}").and(accept(MediaType.APPLICATION_JSON)), handler::delete);
}
}
It should be enough if you mock the EntityHandler
class:
@Test
public void testRoute() {
EntityHandler mockHandler = mock(EntityHandler.class);
RouterFunction<ServerResponse> routerFunction = new EntityRouter().route(mockHandler);
// Set up a mock request
ServerRequest request = mock(ServerRequest.class);
when(request.method()).thenReturn(HttpMethod.GET);
when(request.path()).thenReturn("/getAllEntities");
when(request.headers()).thenReturn(new HttpHeaders());
// Call the router function
routerFunction.route(request).subscribe();
// Verify that the correct method on the mock handler was called
verify(mockHandler).findAll(request);
}
You can use WebTestClient
for reactive stream based rest endpoints. You can find some examples here
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.