Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring, webflux: The getRemoteAddress method of the ServerHttpRequest object returns null when request performed from WebTestClient

I have a controller

@RestController
public class NameController {

    @Autowired
    private NameService nameService;

    @GetMapping("/name")
    public Mono<UploadParamsDto> getName(ServerHttpRequest request) {
            return nameService.getNameByHost(request.getRemoteAddress().getHostName());
    }
}

and i have a test method:

@ExtendWith(SpringExtension.class)
@WebFluxTest(NameControllerTest.class)
@ActiveProfiles("test")
class NameControllerTest {

    @Autowired
    private WebTestClient webClient;

    @Test
    void nameTest() {
        webClient.get().uri("/name")
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus()
                .isOk();
    }
}

When I run the test in order to check my getName method i got NPE because request.getRemoteAddress() returns null, could you please tell me how to mock ServerHttpRequest? (I know that there is MockServerHttpRequest, but I couldn't managed with it)

My purpose is make request.getRemoteAddress().getHostName() return mock value.

like image 262
user10785909 Avatar asked Dec 13 '18 12:12

user10785909


1 Answers

Thanks to everyone. Works in next way:

@ExtendWith(SpringExtension.class)
@WebFluxTest(NameControllerTest.class)
@ActiveProfiles("test")
class NameControllerTest {

    @Autowired
    private ApplicationContext context;

    @Test
    void nameTest() {

        WebTestClient webClient = WebTestClient
                    .bindToApplicationContext(context)
                    .webFilter(new SetRemoteAddressWebFilter("127.0.0.1"))
                    .configureClient()
                    .build();

        webClient.get().uri("/name")
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus()
                .isOk();
    }
}

Where SetRemoteAddressWebFilter is WebFilter:

public class SetRemoteAddressWebFilter implements WebFilter {

    private String host;

    public SetRemoteAddressWebFilter(String host) {
        this.host = host;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        return chain.filter(decorate(exchange));
    }

    private ServerWebExchange decorate(ServerWebExchange exchange) {
        final ServerHttpRequest decorated = new ServerHttpRequestDecorator(exchange.getRequest()) {
            @Override
            public InetSocketAddress getRemoteAddress() {
                return new InetSocketAddress(host, 80);
            }
        };

        return new ServerWebExchangeDecorator(exchange) {
            @Override
            public ServerHttpRequest getRequest() {
                return decorated;
            }
        };
    }
}
like image 116
user10785909 Avatar answered Oct 22 '22 17:10

user10785909