Java Code Examples for org.springframework.test.web.reactive.server.EntityExchangeResult

The following examples show how to use org.springframework.test.web.reactive.server.EntityExchangeResult. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private static String sendRegistration(String managementUrl) {
    String registration = "{ \"name\": \"test\", \"healthUrl\": \"" +
                          managementUrl +
                          "/health\", \"managementUrl\": \"" +
                          managementUrl +
                          "\" }";
    //@formatter:off
    EntityExchangeResult<Map<String, Object>> result = client.post()
                                                            .uri("/instances")
                                                            .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
                                                            .syncBody(registration)
                                                            .exchange()
                                                            .expectStatus().isCreated()
                                                            .expectBody(RESPONSE_TYPE)
                                                            .returnResult();
    //@formatter:on
    assertThat(result.getResponseBody()).containsKeys("id");
    return result.getResponseBody().get("id").toString();
}
 
Example 2
Source Project: Moss   Source File: InstancesControllerIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
private String register() {
    //@formatter:off
    EntityExchangeResult<Map<String, Object>> result = client.post()
                                                            .uri("/instances")
                                                            .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
                                                            .syncBody(register_as_test)
                                                            .exchange()
                                                            .expectStatus().isCreated()
                                                            .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
                                                            .expectHeader().valueMatches("location", "http://localhost:" + localPort + "/instances/[0-9a-f]+")
                                                            .expectBody(RESPONSE_TYPE)
                                                            .returnResult();
    //@formatter:on
    assertThat(result.getResponseBody()).containsKeys("id");
    return result.getResponseBody().get("id").toString();
}
 
Example 3
Source Project: springdoc-openapi   Source File: AbstractSpringDocTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testApp() throws Exception {
	String result = null;
	try {
		EntityExchangeResult<byte[]> getResult = webTestClient.get().uri(Constants.DEFAULT_API_DOCS_URL + groupName).exchange()
				.expectStatus().isOk().expectBody().returnResult();

		result = new String(getResult.getResponseBody());
		String className = getClass().getSimpleName();
		String testNumber = className.replaceAll("[^0-9]", "");

		String expected = getContent("results/app" + testNumber + ".json");
		assertEquals(expected, result, true);
	}
	catch (java.lang.AssertionError e) {
		LOGGER.error(result);
		throw e;
	}
}
 
Example 4
@Test
public void baseRouteShouldListAllImages() {
	// given
	Image alphaImage = new Image("1", "alpha.png");
	Image bravoImage = new Image("2", "bravo.png");
	given(imageService.findAllImages())
		.willReturn(Flux.just(alphaImage, bravoImage));

	// when
	EntityExchangeResult<String> result = webClient
		.get().uri("/")
		.exchange()
		.expectStatus().isOk()
		.expectBody(String.class).returnResult();

	// then
	verify(imageService).findAllImages();
	verifyNoMoreInteractions(imageService);
	assertThat(result.getResponseBody())
		.contains(
			"<title>Learning Spring Boot: Spring-a-Gram</title>")
		.contains("<a href=\"/images/alpha.png/raw\">")
		.contains("<a href=\"/images/bravo.png/raw\">");
}
 
Example 5
@Test
public void baseRouteShouldListAllImages() {
	// given
	Image alphaImage = new Image("1", "alpha.png");
	Image bravoImage = new Image("2", "bravo.png");
	given(imageService.findAllImages())
		.willReturn(Flux.just(alphaImage, bravoImage));

	// when
	EntityExchangeResult<String> result = webClient
		.get().uri("/")
		.exchange()
		.expectStatus().isOk()
		.expectBody(String.class).returnResult();

	// then
	verify(imageService).findAllImages();
	verifyNoMoreInteractions(imageService);
	assertThat(result.getResponseBody())
		.contains(
			"<title>Learning Spring Boot: Spring-a-Gram</title>")
		.contains("<a href=\"/images/alpha.png/raw\">")
		.contains("<a href=\"/images/bravo.png/raw\">");
}
 
Example 6
private String sendRegistration(String managementPath) {
	String managementUrl = this.wireMock.url(managementPath);

	//@formatter:off
	String registration = "{ \"name\": \"test\", " +
						"\"healthUrl\": \"" + managementUrl + "/health\", " +
						"\"managementUrl\": \"" + managementUrl + "\" }";

	EntityExchangeResult<Map<String, Object>> result = this.client.post()
															.uri("/instances")
															.accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
															.bodyValue(registration)
															.exchange()
															.expectStatus().isCreated()
															.expectBody(RESPONSE_TYPE)
															.returnResult();
	//@formatter:on
	assertThat(result.getResponseBody()).containsKeys("id");
	return result.getResponseBody().get("id").toString();
}
 
Example 7
private String register() {
	//@formatter:off
	EntityExchangeResult<Map<String, Object>> result = client.post()
															.uri("/instances")
															.accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
															.bodyValue(register_as_test)
															.exchange()
															.expectStatus().isCreated()
															.expectHeader().contentType(MediaType.APPLICATION_JSON)
															.expectHeader().valueMatches("location", "http://localhost:" + localPort + "/instances/[0-9a-f]+")
															.expectBody(RESPONSE_TYPE)
															.returnResult();
	//@formatter:on
	assertThat(result.getResponseBody()).containsKeys("id");
	return result.getResponseBody().get("id").toString();
}
 
Example 8
Source Project: spring-analysis-note   Source File: ErrorTests.java    License: MIT License 5 votes vote down vote up
@Test // SPR-17363
public void badRequestBeforeRequestBodyConsumed() {
	EntityExchangeResult<Void> result = this.client.post()
			.uri("/post")
			.contentType(MediaType.APPLICATION_JSON)
			.syncBody(new Person("Dan"))
			.exchange()
			.expectStatus().isBadRequest()
			.expectBody().isEmpty();

	byte[] content = result.getRequestBodyContent();
	assertNotNull(content);
	assertEquals("{\"name\":\"Dan\"}", new String(content, StandardCharsets.UTF_8));
}
 
Example 9
Source Project: springdoc-openapi   Source File: AbstractSpringDocTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testApp() throws Exception {
	EntityExchangeResult<byte[]> getResult = webTestClient.get().uri(Constants.DEFAULT_API_DOCS_URL).exchange()
			.expectStatus().isOk().expectBody().returnResult();

	String result = new String(getResult.getResponseBody());
	String className = getClass().getSimpleName();
	String testNumber = className.replaceAll("[^0-9]", "");

	String expected = getContent("results/app" + testNumber + ".json");
	JSONAssert.assertEquals(expected, result, true);
}
 
Example 10
Source Project: springdoc-openapi   Source File: SpringDocApp5Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void transformed_index_with_oauth() throws Exception {
	EntityExchangeResult<byte[]> getResult = webTestClient.get().uri("/webjars/swagger-ui/index.html")
			.exchange()
			.expectStatus().isOk()
			.expectBody().returnResult();
	String result = new String(getResult.getResponseBody());
	assertTrue(result.contains("Swagger UI"));
	String expected = getContent("results/index5");
	assertEquals(expected, result);
}
 
Example 11
Source Project: springdoc-openapi   Source File: SpringDocApp7Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void transformed_index_with_oauth() throws Exception {
	EntityExchangeResult<byte[]> getResult = webTestClient.get().uri("/webjars/swagger-ui/index.html")
			.exchange()
			.expectStatus().isOk()
			.expectBody().returnResult();
	String result = new String(getResult.getResponseBody());
	assertTrue(result.contains("Swagger UI"));
	String expected = getContent("results/index7");
	assertEquals(expected, result);
}
 
Example 12
Source Project: springdoc-openapi   Source File: SpringDocApp6Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void transformed_index_with_oauth() throws Exception {
	EntityExchangeResult<byte[]> getResult = webTestClient.get().uri("/webjars/swagger-ui/index.html")
			.exchange()
			.expectStatus().isOk()
			.expectBody().returnResult();
	String result = new String(getResult.getResponseBody());
	assertTrue(result.contains("Swagger UI"));
	String expected = getContent("results/index6");
	assertEquals(expected, result);
}
 
Example 13
Source Project: java-technology-stack   Source File: ErrorTests.java    License: MIT License 5 votes vote down vote up
@Test // SPR-17363
public void badRequestBeforeRequestBodyConsumed() {
	EntityExchangeResult<Void> result = this.client.post()
			.uri("/post")
			.contentType(MediaType.APPLICATION_JSON_UTF8)
			.syncBody(new Person("Dan"))
			.exchange()
			.expectStatus().isBadRequest()
			.expectBody().isEmpty();

	byte[] content = result.getRequestBodyContent();
	assertNotNull(content);
	assertEquals("{\"name\":\"Dan\"}", new String(content, StandardCharsets.UTF_8));
}
 
Example 14
Source Project: cucumber-rest-steps   Source File: RestSteps.java    License: MIT License 5 votes vote down vote up
private <T> T withAssertion(Supplier<T> supplier) {
  try {
    return supplier.get();
  } catch (AssertionError error) {
    initExpectBody();
    final EntityExchangeResult<byte[]> entityExchangeResult = expectBody.returnResult();
    throw new AssertionError(NestedExceptionUtils.getMostSpecificCause(error).getMessage() + "\n" + entityExchangeResult);
  }
}
 
Example 15
Source Project: cucumber-rest-steps   Source File: RestSteps.java    License: MIT License 5 votes vote down vote up
private void withAssertion(Consumer<Void> consumer) {
  try {
    consumer.accept(null);
  } catch (AssertionError error) {
    initExpectBody();
    final EntityExchangeResult<byte[]> entityExchangeResult = expectBody.returnResult();
    throw new AssertionError(NestedExceptionUtils.getMostSpecificCause(error).getMessage() + "\n" + entityExchangeResult);
  }
}
 
Example 16
@Test
public void postCrudOperations() {
    int randomInt = new Random().nextInt();
    String title = "Post test " + randomInt;
    FluxExchangeResult<Void> postResult = client
        .mutate().filter(basicAuthentication("user", "password")).build()
        .post()
        .uri("/posts")
        .body(BodyInserters.fromObject(Post.builder().title(title).content("content of " + title).build()))
        .exchange()
        .expectStatus().isEqualTo(HttpStatus.CREATED)
        .returnResult(Void.class);

    URI location = postResult.getResponseHeaders().getLocation();
    assertNotNull(location);

    EntityExchangeResult<byte[]> getResult = client
        .get()
        .uri(location)
        .exchange()
        .expectStatus().isOk()
        .expectBody().jsonPath("$.title").isEqualTo(title)
        .returnResult();

    String getPost = new String(getResult.getResponseBody());
    assertTrue(getPost.contains(title));
}
 
Example 17
@Test
public void postCrudOperations() {
    int randomInt = new Random().nextInt();
    String title = "Post test " + randomInt;
    FluxExchangeResult<Void> postResult = client
        .mutate().filter(basicAuthentication("user", "password")).build()
        .post()
        .uri("/posts")
        .body(BodyInserters.fromObject(Post.builder().title(title).content("content of " + title).build()))
        .exchange()
        .expectStatus().isEqualTo(HttpStatus.CREATED)
        .returnResult(Void.class);

    URI location = postResult.getResponseHeaders().getLocation();
    assertNotNull(location);

    EntityExchangeResult<byte[]> getResult = client
        .get()
        .uri(location)
        .exchange()
        .expectStatus().isOk()
        .expectBody().jsonPath("$.title").isEqualTo(title)
        .returnResult();

    String getPost = new String(getResult.getResponseBody());
    assertTrue(getPost.contains(title));
}
 
Example 18
@Test
public void postCrudOperations() {
    int randomInt = new Random().nextInt();
    String title = "Post test " + randomInt;
    FluxExchangeResult<Void> postResult = client
        .mutate().filter(basicAuthentication("user", "password")).build()
        .post()
        .uri("/posts")
        .body(BodyInserters.fromObject(Post.builder().title(title).content("content of " + title).build()))
        .exchange()
        .expectStatus().isEqualTo(HttpStatus.CREATED)
        .returnResult(Void.class);

    URI location = postResult.getResponseHeaders().getLocation();
    assertNotNull(location);

    EntityExchangeResult<byte[]> getResult = client
        .get()
        .uri(location)
        .exchange()
        .expectStatus().isOk()
        .expectBody().jsonPath("$.title").isEqualTo(title)
        .returnResult();

    String getPost = new String(getResult.getResponseBody());
    assertTrue(getPost.contains(title));
}
 
Example 19
@Test
public void postCrudOperations() {
    int randomInt = new Random().nextInt();
    String title = "Post test " + randomInt;
    FluxExchangeResult<Void> postResult = client
        .mutate().filter(basicAuthentication("user", "password")).build()
        .post()
        .uri("/posts")
        .body(BodyInserters.fromObject(Post.builder().title(title).content("content of " + title).build()))
        .exchange()
        .expectStatus().isEqualTo(HttpStatus.CREATED)
        .returnResult(Void.class);

    URI location = postResult.getResponseHeaders().getLocation();
    assertNotNull(location);

    EntityExchangeResult<byte[]> getResult = client
        .get()
        .uri(location)
        .exchange()
        .expectStatus().isOk()
        .expectBody().jsonPath("$.title").isEqualTo(title)
        .returnResult();

    String getPost = new String(getResult.getResponseBody());
    assertTrue(getPost.contains(title));
}
 
Example 20
@Override
protected ResponseDefinitionBuilder getResponseDefinition(
		EntityExchangeResult<?> result) {
	ResponseDefinitionBuilder definition = ResponseDefinitionBuilder
			.responseDefinition().withBody(result.getResponseBodyContent())
			.withStatus(result.getStatus().value());
	addResponseHeaders(definition, result.getResponseHeaders());
	return definition;
}
 
Example 21
@Override
protected Map<String, Object> getConfiguration(EntityExchangeResult<?> result) {
	Field field = ReflectionUtils.findField(
			WebTestClientRestDocumentationConfigurer.class, "configurations");
	ReflectionUtils.makeAccessible(field);
	String index = result.getRequestHeaders()
			.getFirst(WebTestClient.WEBTESTCLIENT_REQUEST_ID);
	@SuppressWarnings("unchecked")
	Map<String, Object> map = (((Map<String, Map<String, Object>>) ReflectionUtils
			.getField(field, null)).get(index));
	if (map == null) {
		return new HashMap<>();
	}
	return map;
}
 
Example 22
Source Project: POC   Source File: BookHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void test01GetAll() {
	EntityExchangeResult<List<Book>> result = this.webTestClient.get().uri("/api/book")
			.accept(MediaType.APPLICATION_JSON).exchange().expectBodyList(Book.class).returnResult();
	assertThat(result.getResponseBody()).size().isGreaterThanOrEqualTo(1);
	assertThat(result.getStatus()).isEqualTo(HttpStatus.OK);
	assertThat(result.getUriTemplate()).isEqualTo("/api/book");

}
 
Example 23
Source Project: tutorials   Source File: UserControllerIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenUserNameIsBaeldung_thenWebFilterIsApplied() {
    EntityExchangeResult<String> result = webTestClient.get().uri("/users/baeldung")
            .exchange()
            .expectStatus().isOk()
            .expectBody(String.class)
            .returnResult();

    assertEquals(result.getResponseBody(), "baeldung");
    assertEquals(result.getResponseHeaders().getFirst("web-filter"), "web-filter-test");
}
 
Example 24
Source Project: tutorials   Source File: PlayerHandlerIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenPlayerNameIsBaeldung_thenWebFilterIsApplied() {
    EntityExchangeResult<String> result = webTestClient.get().uri("/players/baeldung")
            .exchange()
            .expectStatus().isOk()
            .expectBody(String.class)
            .returnResult();

    assertEquals(result.getResponseBody(), "baeldung");
    assertEquals(result.getResponseHeaders().getFirst("web-filter"), "web-filter-test");
}
 
Example 25
Source Project: kafka-graphs   Source File: GraphIntegrationTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testConnectedComponents() {
    webTestClient
        .post()
        .uri("/import")
        .syncBody(generateCCBody())
        .exchange()
        .expectStatus().isOk()
        .expectBody(Void.class);

    GroupEdgesBySourceRequest prepareRequest = new GroupEdgesBySourceRequest();
    prepareRequest.setAlgorithm(GraphAlgorithmType.wcc);
    prepareRequest.setInitialVerticesTopic("initial-cc-vertices");
    prepareRequest.setInitialEdgesTopic("initial-cc-edges");
    prepareRequest.setVerticesTopic("new-cc-vertices");
    prepareRequest.setEdgesGroupedBySourceTopic("new-cc-edges");
    prepareRequest.setAsync(false);

    webTestClient
        .post()
        .uri("/prepare")
        .contentType(MediaType.APPLICATION_JSON)
        .syncBody(prepareRequest)
        .exchange()
        .expectStatus().isOk()
        .expectBody(Void.class);

    GraphAlgorithmCreateRequest createRequest = new GraphAlgorithmCreateRequest();
    createRequest.setAlgorithm(GraphAlgorithmType.wcc);
    createRequest.setVerticesTopic("new-cc-vertices");
    createRequest.setEdgesGroupedBySourceTopic("new-cc-edges");

    EntityExchangeResult<GraphAlgorithmId> createResponse = webTestClient
        .post()
        .uri("/pregel")
        .contentType(MediaType.APPLICATION_JSON)
        .syncBody(createRequest)
        .exchange()
        .expectStatus().isOk()
        .expectBody(GraphAlgorithmId.class)
        .returnResult();
    String id = createResponse.getResponseBody().getId();

    GraphAlgorithmRunRequest runRequest = new GraphAlgorithmRunRequest();

    EntityExchangeResult<GraphAlgorithmStatus> runResponse = webTestClient
        .post()
        .uri("/pregel/{id}", id)
        .contentType(MediaType.APPLICATION_JSON)
        .syncBody(runRequest)
        .exchange()
        .expectStatus().isOk()
        .expectBody(GraphAlgorithmStatus.class)
        .returnResult();

    GraphAlgorithmState.State state = GraphAlgorithmState.State.RUNNING;
    while (state == GraphAlgorithmState.State.RUNNING) {
        EntityExchangeResult<GraphAlgorithmStatus> statusResponse = webTestClient
            .get()
            .uri("/pregel/{id}", id)
            .exchange()
            .expectStatus().isOk()
            .expectBody(GraphAlgorithmStatus.class)
            .returnResult();
        state = statusResponse.getResponseBody().getState();
    }

    FluxExchangeResult<KeyValue> result = webTestClient
        .get()
        .uri("/pregel/{id}/result", id)
        .accept(MediaType.TEXT_EVENT_STREAM)
        .exchange()
        .expectStatus().isOk()
        .returnResult(KeyValue.class);

    Map<String, String> map = result.getResponseBody().collectMap(KeyValue::getKey, KeyValue::getValue).block();
    for (int i = 0; i < 10; i++) {
        assertEquals("0", map.get(String.valueOf(i)));
    }
    for (int i = 10; i < 21; i++) {
        assertEquals("10", map.get(String.valueOf(i)));
    }
}
 
Example 26
Source Project: kafka-graphs   Source File: GraphIntegrationTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testSvdpp() {
    webTestClient
        .post()
        .uri("/import")
        .syncBody(generateSvdppBody())
        .exchange()
        .expectStatus().isOk()
        .expectBody(Void.class);

    GroupEdgesBySourceRequest prepareRequest = new GroupEdgesBySourceRequest();
    prepareRequest.setAlgorithm(GraphAlgorithmType.svdpp);
    prepareRequest.setInitialEdgesTopic("initial-svdpp-edges");
    prepareRequest.setVerticesTopic("new-svdpp-vertices");
    prepareRequest.setEdgesGroupedBySourceTopic("new-svdpp-edges");
    prepareRequest.setAsync(false);

    webTestClient
        .post()
        .uri("/prepare")
        .contentType(MediaType.APPLICATION_JSON)
        .syncBody(prepareRequest)
        .exchange()
        .expectStatus().isOk()
        .expectBody(Void.class);

    Map<String, String> configs = new HashMap<>();
    configs.put(Svdpp.RANDOM_SEED, "0");
    configs.put(Svdpp.ITERATIONS, "3");
    GraphAlgorithmCreateRequest createRequest = new GraphAlgorithmCreateRequest();
    createRequest.setConfigs(configs);
    createRequest.setAlgorithm(GraphAlgorithmType.svdpp);
    createRequest.setVerticesTopic("new-svdpp-vertices");
    createRequest.setEdgesGroupedBySourceTopic("new-svdpp-edges");

    EntityExchangeResult<GraphAlgorithmId> createResponse = webTestClient
        .post()
        .uri("/pregel")
        .contentType(MediaType.APPLICATION_JSON)
        .syncBody(createRequest)
        .exchange()
        .expectStatus().isOk()
        .expectBody(GraphAlgorithmId.class)
        .returnResult();
    String id = createResponse.getResponseBody().getId();

    GraphAlgorithmRunRequest runRequest = new GraphAlgorithmRunRequest();

    EntityExchangeResult<GraphAlgorithmStatus> runResponse = webTestClient
        .post()
        .uri("/pregel/{id}", id)
        .contentType(MediaType.APPLICATION_JSON)
        .syncBody(runRequest)
        .exchange()
        .expectStatus().isOk()
        .expectBody(GraphAlgorithmStatus.class)
        .returnResult();

    GraphAlgorithmState.State state = GraphAlgorithmState.State.RUNNING;
    while (state == GraphAlgorithmState.State.RUNNING) {
        EntityExchangeResult<GraphAlgorithmStatus> statusResponse = webTestClient
            .get()
            .uri("/pregel/{id}", id)
            .exchange()
            .expectStatus().isOk()
            .expectBody(GraphAlgorithmStatus.class)
            .returnResult();
        state = statusResponse.getResponseBody().getState();
    }

    FluxExchangeResult<KeyValue> result = webTestClient
        .get()
        .uri("/pregel/{id}/result", id)
        .accept(MediaType.TEXT_EVENT_STREAM)
        .exchange()
        .expectStatus().isOk()
        .returnResult(KeyValue.class);

    NavigableMap<CfLongId, String> map = (NavigableMap<CfLongId, String>) result.getResponseBody().collectMap(
        kv -> new CfLongId(kv.getKey()),
        KeyValue::getValue,
        TreeMap::new
    ).block();
    assertEquals("(1, 0)=(0.11611404, [0.006397, 0.008010])", map.firstEntry().toString());
    assertEquals("(20, 1)=(0.6374174, [0.007310, 0.002405])", map.lastEntry().toString());
}
 
Example 27
@Override
public void accept(EntityExchangeResult<byte[]> result) {
	configure(result);
}
 
Example 28
@Override
protected Request getWireMockRequest(EntityExchangeResult<?> result) {
	return new WireMockHttpRequestAdapter(result);
}
 
Example 29
@Override
protected MediaType getContentType(EntityExchangeResult<?> result) {
	return result.getRequestHeaders().getContentType();
}
 
Example 30
@Override
protected byte[] getRequestBodyContent(EntityExchangeResult<?> result) {
	return result.getRequestBodyContent();
}