在测试方法中,接收到org.springframework.web.reactive.function.client.ClientRequest的实例。

我想验证其HttpMethod,URI和正文。

很明显,如何获得除身体以外的所有东西。

ClientRequest request = makeInstance(...);

assertEquals(HttpMethod.POST, request.method());
assertEquals("somewhere/else", request.url().toString());

// ? unclear how to extract body using the BodyInserter

BodyInserter<?, ? super ClientHttpRequest> inserter = request.body();

inserter.insert(%outputMessage%, %context%);


我在Spring how BodyInserters are tested的来源中找到了。大致了解如何创建BodyInserter.Context(第二个参数),但是我不明白如何构造第一个参数,因此可以通过它提取请求正文。

请显示一种从ClientRequest实例获取请求正文的常规方法(或至少可用的方法)。

最佳答案

因此,对于这种简单的情况来说有点复杂,但是我花了5个类来从ClientRequest中提取主体。对于这样简单的问题似乎太多了。

我仍然很好奇是否有一个简短的解决方案,因此,欢迎您为这个问题提出另一个答案,以便我接受。

不幸的是,必须说ClientRequestBodyInsertersorg.springframework.web.reactive.***的大多数其他内容的设计还有很大的改进空间。目前,这只是一堆接口,每个接口都有很多方法,根据这些类,通常需要花费很多精力来测试代码。

使这种方法起作用的主要目标是:

static <T> T extractBody(ClientRequest request, Class<T> clazz) {

  InsertionReceiver<T> receiver = InsertionReceiver.forClass(clazz);
  return receiver.receiveValue(request.body());
}


这是InsertionReceiver的实现:



1。

import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.web.reactive.function.BodyInserter;

public interface InsertionReceiver<T> {

  T receiveValue(BodyInserter<?, ? extends ReactiveHttpOutputMessage> bodyInserter);

  static <T> InsertionReceiver<T> forClass(Class<T> clazz) {
    return new SimpleValueReceiver<>(clazz);
  }
}




2。

import java.util.concurrent.atomic.AtomicReference;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.web.reactive.function.BodyInserter;

class SimpleValueReceiver<T> implements InsertionReceiver<T> {

  private static final Object DUMMY = new Object();

  private final Class<T> clazz;
  private final AtomicReference<Object> reference;

  SimpleValueReceiver(Class<T> clazz) {
    this.clazz = clazz;
    this.reference = new AtomicReference<>(DUMMY);
  }

  @Override
  public T receiveValue(BodyInserter<?, ? extends ReactiveHttpOutputMessage> bodyInserter) {
    demandValueFrom(bodyInserter);

    return receivedValue();
  }

  private void demandValueFrom(BodyInserter<?, ? extends ReactiveHttpOutputMessage> bodyInserter) {
    var inserter = (BodyInserter<?, ReactiveHttpOutputMessage>) bodyInserter;

    inserter.insert(
        MinimalHttpOutputMessage.INSTANCE,
        new SingleWriterContext(new WriteToConsumer<>(reference::set))
    );
  }

  private T receivedValue() {
    Object value = reference.get();
    reference.set(DUMMY);

    T validatedValue;

    if (value == DUMMY) {
      throw new RuntimeException("Value was not received, Check your inserter worked properly");
    } else if (!clazz.isAssignableFrom(value.getClass())) {
      throw new RuntimeException(
          "Value has unexpected type ("
              + value.getClass().getTypeName()
              + ") instead of (" + clazz.getTypeName() + ")");
    } else {
      validatedValue = clazz.cast(value);
    }

    return validatedValue;
  }
}




3。

class WriteToConsumer<T> implements HttpMessageWriter<T> {

  private final Consumer<T> consumer;
  private final List<MediaType> mediaTypes;

  WriteToConsumer(Consumer<T> consumer) {
    this.consumer = consumer;
    this.mediaTypes = Collections.singletonList(MediaType.ALL);
  }

  @Override
  public List<MediaType> getWritableMediaTypes() {
    return mediaTypes;
  }

  @Override
  public boolean canWrite(ResolvableType elementType, MediaType mediaType) {
    return true;
  }

  @Override
  public Mono<Void> write(
      Publisher<? extends T> inputStream,
      ResolvableType elementType,
      MediaType mediaType,
      ReactiveHttpOutputMessage message,
      Map<String, Object> hints
  ) {
    inputStream.subscribe(new OneValueConsumption<>(consumer));
    return Mono.empty();
  }
}




4。

class MinimalHttpOutputMessage implements ReactiveHttpOutputMessage {

  public static MinimalHttpOutputMessage INSTANCE = new MinimalHttpOutputMessage();

  private MinimalHttpOutputMessage() {
  }

  @Override
  public HttpHeaders getHeaders() {
    return HttpHeaders.EMPTY;
  }

  // other overridden methods are omitted as they do nothing,
  // i.e. return null, false, or have empty bodies
}




5,

class OneValueConsumption<T> implements Subscriber<T> {

  private final Consumer<T> consumer;
  private int remainedAccepts;

  public OneValueConsumption(Consumer<T> consumer) {
    this.consumer = Objects.requireNonNull(consumer);
    this.remainedAccepts = 1;
  }

  @Override
  public void onSubscribe(Subscription s) {
    s.request(1);
  }

  @Override
  public void onNext(T o) {
    if (remainedAccepts > 0) {
      consumer.accept(o);
      remainedAccepts -= 1;
    } else {
      throw new RuntimeException("No more values can be consumed");
    }
  }

  @Override
  public void onError(Throwable t) {
    throw new RuntimeException("Single value was not consumed", t);
  }

  @Override
  public void onComplete() {
    // nothing
  }
}




6。

class SingleWriterContext implements BodyInserter.Context {

  private final List<HttpMessageWriter<?>> singleWriterList;

  SingleWriterContext(HttpMessageWriter<?> writer) {
    this.singleWriterList = List.of(writer);
  }

  @Override
  public List<HttpMessageWriter<?>> messageWriters() {
    return singleWriterList;
  }

  @Override
  public Optional<ServerHttpRequest> serverRequest() {
    return Optional.empty();
  }

  @Override
  public Map<String, Object> hints() {
    return null;
  }
}

09-27 14:27