简体   繁体   English

如何为 spring webflux 路由器编写单元测试?

[英]how to write unit tests for spring webflux router?

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?我有以下类型的 EntityRouter,现在我的问题是没有自动连接的处理程序,我如何模拟和编写 junit 单元测试(非集成)这样的端点?

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.注意:对于 controller,这对我来说在概念上很简单,因为如果我们使用 spring-web-mvc,我可以模拟通常在 controller 中自动装配的服务。

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:如果你模拟EntityHandler类就足够了:

@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.您可以将WebTestClient用于基于 stream 的响应式 rest 端点。 You can find some examples here你可以在这里找到一些例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM