Skip to content

Instantly share code, notes, and snippets.

@tsgautier
Created November 2, 2017 18:21
Show Gist options
  • Save tsgautier/d31b0b07b595594e5df58f78cc5f5d4e to your computer and use it in GitHub Desktop.
Save tsgautier/d31b0b07b595594e5df58f78cc5f5d4e to your computer and use it in GitHub Desktop.
@ContextConfiguration
@SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension.class)
public class WebClientTest {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(WebClient.class);
private static final String BODY = "this is the body";
private static final String ENDPOINT = "endpoint";
@LocalServerPort
int port;
private StringDecoder stringDecoder = StringDecoder.textPlainOnly(false);
@Test
void testTwoStreamsFromBody() {
WebClient webclient = WebClient.create("http://localhost:" + port);
Flux<DataBuffer> body = webclient
.get()
.uri(ENDPOINT)
.exchange()
.doOnNext(this::validateIsSuccess)
.map(response -> response.bodyToFlux(DataBuffer.class))
.block()
.log()
.cache() // comment out to get duplicate subscribe error, leave in to get ref cnt error
;
StepVerifier.create(
Flux.from(decodeToString(body))
.concatWith(decodeToString(body))
)
.expectNext(BODY)
.expectNext(BODY)
.verifyComplete();
}
private void validateIsSuccess(ClientResponse r) {
if (!r.statusCode().is2xxSuccessful()) throw new RuntimeException("Received " + r.statusCode());
}
private Mono<String> decodeToString(Flux<DataBuffer> stream) {
return stringDecoder.decode(stream, ResolvableType.forClass(String.class), null, null)
.reduce(new StringBuilder(), (builder, e) -> { builder.append(e); return builder; })
.map(StringBuilder::toString);
}
@RestController
static class Service {
@GetMapping(ENDPOINT)
public String endpoint() {
logger.info("endpoint called");
return BODY;
}
}
@Configuration
@SpringBootApplication
static class TestConfiguration {
@Bean
Service service() { return new Service(); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment