vendredi 26 mars 2021

How to mock a WebClient in Spring?

I have a blog BlogServiceBlient that calls a Blog Service and returns a list of blogs. I want to write a unit test for searchBlogs method in the BlogService Client How can I Mock a WebClient with Mockito?

import java.util.ArrayList;
import java.util.List;

/**
 * The type Blog service client.
 */
@Component
public class BlogServiceClient {

  private final WebClient blogsClient;

  /**
   * Instantiates a new Blog service client.
   *
   * @param blogServiceClient the blog service client
   */
  @Autowired
  public BlogServiceClient(WebClient blogServiceClient) {
    this.blogsClient = blogServiceClient;
  }

  /**
   * Search blogs list.
   *
   * @param searchBlogsRequest the search blogs request
   * @return the list
   */
  public List<BlogDetailsResponse> searchBlogs(final SearchBlogsRequest searchBlogsRequest) {
    return blogsClient
        .post()
        .uri("/searchBlogs")
        .body(BodyInserters.fromValue(searchBlogsRequest))
        .retrieve()
        .bodyToFlux(BlogDetailsResponse.class)
        .collectList()
        .block();
  }
}

Aucun commentaire:

Enregistrer un commentaire