我有一个像这样的控制器:
@RestController
public class ApiController {
@GetMapping(path = "/somethings")
public Mono<String> getThings(final WebSession webSession) {
if (!webSession.getAttribute("state").equals("started")) {
throw new RuntimeException("Cannot make API calls until session has started");
}
// Make api calls here...
}
}
在我的@WebFluxTest中,我需要访问网络会话,将“state”属性设置为“started”。
有没有办法在@WebFluxTest中访问和更新WebSession?
答案 0 :(得分:0)
找到了答案。
WebTestClient有一个 mutateWith 方法,您可以在其中传递 WebTestClientConfigurer 。
通过创建自定义WebTestClientConfigurer,可以添加会话属性。
public class SessionMutator implements WebTestClientConfigurer {
private static Map<String, Object> sessionMap;
private SessionMutator(final Map<String, Object> sessionMap) {
this.sessionMap = sessionMap;
}
public static SessionMutator sessionMutator(final Map<String, Object> sessionMap) {
return new SessionMutator(sessionMap);
}
@Override
public void afterConfigurerAdded(final WebTestClient.Builder builder,
final WebHttpHandlerBuilder httpHandlerBuilder,
final ClientHttpConnector connector) {
final SessionMutatorFilter sessionMutatorFilter = new SessionMutatorFilter();
httpHandlerBuilder.filters(filters -> filters.add(0, sessionMutatorFilter));
}
public static ImmutableMap.Builder<String, Object> sessionBuilder() {
return new ImmutableMap.Builder<String, Object>();
}
private static class SessionMutatorFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain webFilterChain) {
return exchange.getSession()
.doOnNext(webSession -> webSession.getAttributes().putAll(sessionMap))
.then(webFilterChain.filter(exchange));
}
}
}
然后在@WebFluxTest中,可以执行以下操作:
webTestClient.mutateWith(sessionMutator(sessionBuilder().put("sessionKey", "sessionValue").build()))