In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the knowledge of "how to create WebTestClient". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
WebTestClient
WebTestClient is a thin shell around WebClient that can be used to execute requests and expose dedicated fluent API to validate responses. WebTestClient binds to the WebFlux application by using mock requests and responses, or it can test any Web server over a HTTP connection.
3.7.1 installation
To create a WebTestClient, you must select one of several server setup options. In fact, you are configuring the WebFlux application to bind to the URL, or you are using URL to connect to the running server.
Bind to controller
The following example shows how to create server settings to test one @ Controller at a time:
Client = WebTestClient.bindToController (new TestController ()) .build ()
The previous example loads the WebFlux Java configuration and registers the given controller. Using mock request and response objects, you can test the generated WebFlux application without a HTTP server. There are more ways to customize the default WebFlux Java configuration on the builder.
Bind to router featur
The following example shows how to set up a server through RouterFunction:
RouterFunction route =... client = WebTestClient.bindToRouterFunction (route). Build ()
Internally, the configuration is passed to RouterFunctions.toWebHandler. Using mock request and response objects, you can test the generated WebFlux application without a HTTP server.
Bind to ApplicationContext
The following example shows how to set up the server through the Spring configuration of the application or part of its subset:
@ SpringJUnitConfig (WebConfig.class) / / 1class MyTests {WebTestClient client; @ BeforeEach void setUp (ApplicationContext context) {/ / 2 client = WebTestClient.bindToApplicationContext (context) .build (); / / 3}}
Specify the configuration to load
Injection configuration
Create WebTestClient
Internally, the configuration is passed to the WebHttpHandlerBuilder to establish the request processing chain. For more details, see WebHandler API. Using mock request and response objects, you can test the generated WebFlux application without a HTTP server.
Bind to server
The following server settings options allow you to connect to a running server:
Client = WebTestClient.bindToServer () .baseUrl ("http://localhost:8080").build();
Client builder
In addition to the server settings described above, you can also configure client options, including basic URL, default headers, client filters, and so on. For all other servers, you need to use configureClient () to transition from server configuration to client configuration, as follows:
Client = WebTestClient.bindToController (new TestController ()) .inherreClient () .baseUrl ("/ test") .build ()
3.7.2 write test
WebTestClient provides the same API as WebClient until the request is executed using exchange (). Exchange () is followed by a linked API workflow that validates the response.
Typically, the response status and header are declared first, as follows:
Client.get () .uri ("/ persons/1") .accept (MediaType.APPLICATION_JSON) .exchange () .returtStatus () .isOk () .returtHeader () .contentType (MediaType.APPLICATION_JSON)
Then you specify how to decode and use the response subject:
ExpectBody (Class): decoded to a single object.
ExpectBodyList (Class): decodes and collects objects into List.
ExpectBody (): decode to byte [] to get the JSON content or an empty body.
You can then use built-in assertions for the subject. The following example shows one method:
Client.get (). Uri ("/ persons") .exchange () .returtStatus (). IsOk () .returtBodyList (Person.class) .hasSize (3) .accountStatus (person)
You can also go beyond built-in assertions and create your own assertions, as shown in the following example:
Import org.springframework.test.web.reactive.server.expectBodyclient.get (). Uri ("/ persons/1") .exchange () .returtStatus (). IsOk () .returtBody (Person.class) .expeceWith (result-> {/ / custom assertions (e.g. AssertJ). });
You can also exit the workflow and get the results, as shown below:
EntityExchangeResult result = client.get () .uri ("/ persons/1") .exchange () .returtStatus (). IsOk () .returtBody (Person.class) .returnResult ()
When you need to use generic decoding for the target type, look for overloaded methods that accept ParameterizedTypeReference instead of Class.
No content
If the response has no content (or you don't care), use Void.class to ensure that resources are released. The following example shows how to do this:
Client.get () .uri ("/ persons/123") .exchange () .returtStatus () .isNotFound () .returtBody (Void.class)
Or, if you want to assert that there is no response, you can use code similar to the following:
Client.post () .uri ("/ persons") .body (personMono, Person.class) .exchange () .returtStatus () .isCreated () .accountBody () .isEmpty ()
JSON content
When you use ExpectBody (), the response is in the form of byte []. This is useful for the original content declaration. For example, you can use JSONAssert to validate JSON content, as follows:
Client.get () .uri ("/ persons/1") .exchange () .returtStatus () .isOk () .returtBody () .json ("{\" name\ ":\" Jane\ "}")
You can also use JSONPath expressions, as shown below:
Client.get () .uri ("/ persons") .exchange () .returtStatus (). IsOk () .returtBody () .jsonPath ("$[0] .name") .isEqualTo ("Jane") .jsonPath ("$[1] .name") .isEqualTo ("Jason")
Streaming response
To test an infinite stream (for example, "text/event-stream" or "application/stream + json"), you need to exit the linked API immediately after the response status and response header assertion (by using returnResult), as shown in the following example:
FluxExchangeResult result = client.get () .uri ("/ events") .accept (TEXT_EVENT_STREAM) .exchange () .accountStatus () .isOk () .returnResult (MyEvent.class)
Now, you can use Flux to assert the decoded object when it reaches it, and then cancel it at some point when the test target is reached. We recommend using StepVerifier in the reactor test module to do this, as shown in the following example:
Flux eventFlux = result.getResponseBody (); StepVerifier.create (eventFlux) .expectNext (person) .accountNextCount (4) .roomeNextWith (p->...) .thenCancel () .roomtNextCount (4).
Request body
When it comes to build requests, WebTestClient provides the same API as WebClient, and the implementation is mainly simple delivery.
This is the end of "how to create WebTestClient". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.