10 Ağustos 2021 Salı

SpringCloud Feign Feign Sınıfı

Giriş
SpringCloud Feign projesindeki anotasyonları kullanmadan kütüphaneyi direkt kullanmak mümkün.

Örnek
Elimizde şöyle bir arayüz olsun
@Headers("Accept: application/json")
public interface BookClient {

    @RequestLine("POST")
    @Headers("Content-Type: application/json")
    void create(Book book);

    @RequestLine("GET")
    List<Book> findAll();

    @RequestLine("GET /{id}")
    Book findById(@Param("id") Integer id);

    @RequestLine("DELETE /{id}")
    void remove(@Param("id") Integer id);

    @RequestLine("PUT /{id}")
    @Headers("Content-Type: application/json")
    void update(@Param("id") Integer id, Book book);
}
Şöyle yaparız
@Slf4j
public class FeignTest {
  private static BookClient bookClient;
  private static WireMockServer wireMockServer;
  private final static String FOLDER = "src/test/resources/wiremock";

  @BeforeAll
  public static void setup() {
    bookClient = Feign.builder().client(new OkHttpClient())
      .encoder(new GsonEncoder()).decoder(new GsonDecoder())
      .logger(new Slf4jLogger(BookClient.class)).logLevel(Logger.Level.FULL)
      .target(BookClient.class, "http://localhost:57002/api/books");

    wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig()
      .withRootDirectory(FOLDER).port(57002)
      .notifier(new ConsoleNotifier(true)));
      wireMockServer.start();
  }

  @Test
  public void findById() throws Exception {
    wireMockServer.stubFor(get(urlPathEqualTo("/api/books/1"))
      .willReturn(aResponse().withBodyFile("book1.json")));

    Book book = bookClient.findById(1);
    assertThat(book.getAuthor(), equalTo("Orson S. Card"));
    wireMockServer.verify(1, getRequestedFor(urlEqualTo("/api/books/1"))
      .withHeader("Accept", WireMock.equalTo("application/json")));
  }
}

Hiç yorum yok:

Yorum Gönder