Spring Cloud Gateway自定义过滤器工厂的单元测试

时间:2019-12-20 20:36:57

标签: java spring spring-cloud spring-cloud-gateway

我已经为Cloud Gateway实现了自定义过滤器工厂。但是,我无法弄清楚编写单元测试用例的方式。 在探索默认的Filter Factories测试用例时,我发现大多数工厂测试类扩展了BaseWebClientTests和测试包中的其他类。

我的问题是,我应该将那些中间测试类复制粘贴到我的本地测试包中吗?这里的社区建议是什么?

1 个答案:

答案 0 :(得分:0)

这是我的结果,供您参考

class CustomGatewayFilterFactoryTest {

    @Autowired
    private CustomGatewayFilterFactory factory;

    private ServerWebExchange exchange;
    private GatewayFilterChain filterChain = mock(GatewayFilterChain.class);
    private ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor.forClass(ServerWebExchange.class);

    @BeforeEach
    void setup() {
        when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());
    }

    @Test
    void customTest() {
        MockServerHttpRequest request = MockServerHttpRequest.get(DUMMY_URL).build();
        exchange = MockServerWebExchange.from(request);
        GatewayFilter filter = factory.apply(YOUR_FACTORY_CONFIG);
        filter.filter(exchange, filterChain);
        // filter.filter(exchange, filterChain).block(); if you have any reactive methods

        ServerHttpRequest actualRequest = captor.getValue().getRequest();

        // Now you can assert anything in the actualRequest
        assertEquals(request, actualRequest);
    }

}