ในบทความนี้ เราจะเรียนรู้เกี่ยวกับ Rest Assured ไลบรารี Java สำหรับทดสอบ REST API
Rest Assured คืออะไร?
Rest Assured เป็นไลบรารี Java ที่ใช้ยืนยัน (verify) REST APIs ทำหน้าที่เป็น Headless Client ติดต่อกับ REST Web Services โดยตรง ไม่ต้องผ่าน Browser
ความสามารถหลัก
- ทดสอบ Response: Status Code, Body, Message, Headers
- รองรับ HTTP Methods: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
- Validate JSON/XML Response ด้วย JsonPath, XmlPath
- Authentication: Basic, Digest, OAuth, API Key
- Schema Validation (JSON Schema)
- Data-driven Testing
การผสานรวม (Integration)
- Build Tools: Maven, Gradle
- Test Frameworks: JUnit 4/5, TestNG
- CI/CD: Jenkins, GitLab CI, GitHub Actions
ทำไมต้องใช้ Rest Assured?
- Free & Open Source: ไม่มีค่า License
- Fluent API: เขียนโค้ดอ่านง่าย แบบ Method Chaining
- Backend Testing: ทดสอบ API ก่อนมี UI ลดต้นทุนแก้บั๊ก
- Powerful Matching: Hamcrest Matchers สำหรับ Assertion
- Documentation ดี: มีเอกสารและ Community ใหญ่
ตัวอย่างโค้ดพื้นฐาน
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class APITest {
@Test
public void testGetUser() {
given()
.baseUri("https://jsonplaceholder.typicode.com")
.header("Content-Type", "application/json")
.when()
.get("/users/1")
.then()
.statusCode(200)
.body("name", equalTo("Leanne Graham"))
.body("email", containsString("@"));
}
}
การเพิ่ม Dependency (Maven)
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version> <!-- ตรวจสอบเวอร์ชันล่าสุด -->
<scope>test</scope>
</dependency>
สรุป
Rest Assured เป็นเครื่องมือมาตรฐานอุตสาหกรรมสำหรับ API Testing ใน Java เหมาะสำหรับ Backend Testing, Contract Testing และ Integration Testing