28 Mart 2023 Salı

WireMock WireMockServer Sınıfı

Giriş
Şu satırı dahil ederiz
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock.*
import com.github.tomakehurst.wiremock.core.WireMockConfiguration
Mocks From Static Files Kullanımı
HTTP File Server Gibi Kullanım içindir. Yani statik dosyalar içindir. Açıklaması şöyle
The easiest way to create a mock is to create a folder with the name __files and add files into it.
Now we can perform a GET request using the URL:
http://<mock-server-host>:<port>/file-name.file-extension
Örnek 
Şöyle yaparız
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;

import com.github.tomakehurst.wiremock.WireMockServer;

new WireMockServer(options()
  .usingFilesUnderClasspath("src/main/resources/wiremock")
  .port(8000)
).start();
src/main/resources/__files altındaki dosyaları sunmaya başlar. http://localhost:8080/customer.json dosyasını istersek src/main/resources/__files/customers.json dosyasını gönderir.

Mappings Kullanımı
 Açıklaması şöyle
Most of the time we will need mocks that are more advanced than we can get from static files. To create more advanced mocks we can use mappings. Mapping is a file in a JSON format, located in a special folder called mappings, that describes e request and response. This description contains the request URL, request method, request, and response body, headers, and response status. 
Eğer gerekiyorsa POST göndererek, çalışma esnasında mapping yaratmak ta mümkün.

Örnek 
src/main/resources/__files dizininde healthcheck.json isimli dosya şöyle olsun
{
  "request": {
    "method": "GET",
    "url": "/actuator/health"
  },
  "response": {
    "status": 200,
    "body": "{\"status\":\"UP\"}",
    "headers": {
      "Content-Type": "application/json"
    }
  }
}
http://localhost:8080//actuator/health adresine istek gönderirsek, cevap alırız

Response Templating Kullanımı
Açıklaması şöyle
There are cases when we want to return inside the response some data received in the request body, path, or headers. For example, we perform a request to obtain a customer by id:

http://<mock-server-host>:<port>/customers/{id}
And we want to receive a response body, containing the id of the customer passed as a path parameter. To be able to achieve that we can use Handlebars templates.
Transformers Kullanımı
Açıklama burada

Callback Kullanımı
Açıklama burada

Metodlar
constructor - WireMockConfiguration
Şöyle yaparız. Her testing başında bu sınıfın start() ve stop() metodlarını çağırmak gerekir.
var wiremockServer = WireMockServer(WireMockConfiguration.options().dynamicPort())
stubFor metodu
get + willReturn + withBody
get + willReturn + withBodyFile

get + willReturn + aResponse + Çeşitli Delay Yöntemleri

withBody Kullanımı
Örnek
Şöyle yaparız
class HttpTest {

  private WireMockServer server;

  @BeforeEach
  void setUp() {
    server = new WireMockServer(WireMockConfiguration.wireMockConfig().dynamicPort());
    server.start();
  }

  @Test
  void test() throws Exception {
    mockWebServer();

    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("http://localhost:" + server.port() + "/my/resource"))
                    .build();
    HttpResponse<String> response = client.send(request,
                                                HttpResponse.BodyHandlers.ofString());

    assertEquals("TheGreatAPI.com", response.body());
  }

  private void mockWebServer() {
    server.stubFor(get("/my/resource")
                  .willReturn(ok()
                  .withBody("TheGreatAPI.com")));
  }

  @AfterEach
  void tearDown() {
    server.shutdownServer();
  }
}
withBodyFile Kullanımı
Örnek
Şöyle yaparız
@Slf4j
public class FeignTest {
  private BookClient bookClient;
  private WireMockServer wireMockServer;
  private final static String FOLDER = "src/test/resources/wiremock";

  @BeforeAll
  public 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