Skip to content

Instantly share code, notes, and snippets.

@up1
Created March 30, 2025 14:32
Show Gist options
  • Save up1/f4f6e52156657385efbaaffc37213a51 to your computer and use it in GitHub Desktop.
Save up1/f4f6e52156657385efbaaffc37213a51 to your computer and use it in GitHub Desktop.
Spring Boot testing with WireMock
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.wiremock.spring.EnableWireMock;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(
classes = DemoGatewayTest.AppConfiguration.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableWireMock
class DemoGatewayTest {
@Value("${wiremock.server.baseUrl}")
private String wireMockUrl;
@Autowired
private TestRestTemplate restTemplate;
@Test
@DisplayName("ทำการจำลอง GET /ping แล้ว return ค่า pong กลับมา")
void case01() {
// Arrange
stubFor(get("/ping").willReturn(ok("pong")));
// Act
ResponseEntity<String> response = restTemplate.getForEntity(wireMockUrl + "/ping", String.class);
// Assert
assertEquals("pong", response.getBody());
}
@Test
@DisplayName("ทำการจำลอง GET /ping แล้ว return status code = 404 กลับมา")
void case02() {
// Arrange
stubFor(get("/ping").willReturn(notFound()));
// Act
ResponseEntity<String> response = restTemplate.getForEntity(wireMockUrl + "/ping", String.class);
// Assert
assertEquals(404, response.getStatusCode().value());
}
@Test
@DisplayName("ทำการจำลอง GET /ping ให้ช้ากว่า โดย return ผลกลับมาภายในเวลา 5 วินาที")
void case03() {
// Arrange
stubFor(get("/ping").willReturn(ok("pong").withFixedDelay(5000)));
// Act
ResponseEntity<String> response = restTemplate.getForEntity(wireMockUrl + "/ping", String.class);
// Assert
assertEquals("pong", response.getBody());
}
@SpringBootApplication
static class AppConfiguration {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment