How to write unit test for a WebFilter that is writing a Reactor Context? Specifically, what and how do I mock?

Viewed 2292

Suppose I have this simple webfilter that just writes a reactor context

WebFilter filter = (serverWebExchange, webFilterChain) ->
    webFilterChain
        .filter(serverWebExchange)
        .contextWrite(Context.of("my-key", true));

I'd imagine the test will look something like this:

StepVerifier.create(filter.filter(serverWebExchange, webFilterChain)
    .expectAccessibleContext()
    .hasKey("my-key")
    .then()
    .verifyComplete();

But I'm not sure how to mock the webFilterChain to make sure the Context is written.

Mockito.when(webFilterChain.filter(any()).thenReturn(???)

Any ideas?

2 Answers

I have the same problem and this is my solution

WebFilterChain filterChain = filterExchange -> Mono.empty();
MockServerWebExchange exchange = MockServerWebExchange.from(
    MockServerHttpRequest
        .get("/your-url")
        .header("my-key", "value"));

StepVerifier.create(yourFilter.filter(exchange, filterChain))
    .expectAccessibleContext()
    .hasKey("my-key")
    .then()
    .verifyComplete();

https://github.com/spring-projects/spring-framework/blob/main/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsWebFilterTests.java

Because the method webFilterChain.filter(any()) does not return anything (it is a void method), I would suggest to verify if the method was called:

Mockito.verify(webFilterChain, times(1)).filter(any());
Related