Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing for Spring Cloud Gateway Custom Filter Factory

I have implemented the custom filter factories for Cloud Gateway. However, I couldn't figure out the way to write unit testcases. While exploring the default Filter Factories test cases, I found that majority of factories test classes extends BaseWebClientTests and other classes which are in test package.

My question is that shall I copy paste those intermediate test classes to my local test package? What's community recommendation here?

like image 808
Rahul Sharma Avatar asked Oct 20 '25 04:10

Rahul Sharma


1 Answers

Here is my result, for your information

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);
    }

}
like image 185
Xuanyu Avatar answered Oct 21 '25 18:10

Xuanyu