Spring,Webflux:当从WebTestClient执行请求时,ServerHttpRequest对象的getRemoteAddress方法返回null

时间:2018-12-13 12:15:56

标签: spring spring-test spring-webflux

我有一个控制器

@RestController
public class NameController {

    @Autowired
    private NameService nameService;

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

我有一个测试方法:

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

当我运行测试以检查我的getName方法时,我得到了NPE,因为 request.getRemoteAddress()返回null,请告诉我如何模拟ServerHttpRequest吗? (我知道有MockServerHttpRequest,但我无法对其进行管理)

我的目的是使request.getRemoteAddress()。getHostName()返回模拟值。

2 个答案:

答案 0 :(得分:1)

感谢大家。 可通过以下方式工作:

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

其中SetRemoteAddressWebFilter是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;
            }
        };
    }
}

答案 1 :(得分:0)

使用@WebFluxTest运行测试并不涉及真正的服务器,您已经知道了。

但是获得NullPointerException的感觉仍然不正确-您可以在https://jira.spring.io上对此提出问题吗?我认为您不必解决此问题,但是Spring Framework可能应该提供一些基础结构来“模拟”该信息。