Test class

Create a normal test class, as follows. Use the @Autowired annotation to inject the WebTestClient instance in your test class:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class WebclientDemoApplicationTests {
@Autowired
private WebTestClient webTestClient;
@Test
public void getAllMovies() {
System.out.println("Test 1 executing getAllMovies");
webTestClient.get().uri("/api/movie")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBodyList(Movie.class);
}
@Test
public void saveMovie() {
System.out.println("Test 2 executing saveMovie");
Movie movie = new Movie(Long.valueOf(10), "Test Title", "Test Genre");
webTestClient.post().uri("/api/movie")
.body(Mono.just(movie), Movie.class)
.exchange()
.expectStatus().isOk()
.expectBody();
}
}

The WebTestClient object's functionality is similar to WebClient, as seen earlier. We can check for various properties in the response to ascertain what we want to test. In the preceding example, for the first test, we are firing a GET request and checking for OK status, an application/JSON content type header, and, finally, a body having a list of Movie objects. In the second test, we are firing a POST request with a Movie object as the body, and, expecting an OK status and an empty body.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.229.143