Cara Nambah Lapisan Timun ing Ndhuwur Tes API sing wis REST

Posting iki menehi pandhuan langkah-langkah babagan cara nambah lapisan timun ing ndhuwur tes api sing ditulis kanthi Jaminan.

DSL REST-sure wis nyedhiyakake tes tes gaya BDD ing format Diwenehake Nalika Sampeyan, nanging isih dikubur ing kode kasebut. Kanthi tembung liyane, yen sampeyan pengin ndeleng skenario apa sing dibahas, sampeyan isih kudu mriksa tes api lan maca kode kasebut. Ora ana file fitur.

Tujuane kiriman iki yaiku kanggo refaktor tes api sing wis JAMINAN kanthi nambah file timun lan fitur, saengga skenario bisa diwaca kanthi luwih jelas tanpa kudu ndeleng kode sing ndasari.




Tes API sing paling apik

Ing conto iki, kita bakal nulis kode kanggo nyoba api nggawe pangguna.

Kaping pisanan, kita duwe Tes REST mandiri lan JUnit sing mandhiri, sing dununge ing:


src/test/java/io.devqa/scenarios



import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; import org.junit.jupiter.api.*; import static io.restassured.RestAssured.given; public class UserTests {
private static String path;
private static String validRequest = '{ ' +

' 'username': 'test-api-user', ' +

' 'email': 'test-api-user@email.com', ' +

' 'password': 'Passw0rd123!', ' +

' 'name': 'Test Api-User' }';
@BeforeAll
public static void setConfig() {
RestAssured.baseURI = 'https://localhost:8080';
path = '/users';
}
@Test
public void shouldBeAbleToCreateNewUser() {
Response createUser = given()


.auth()


.preemptive()


.basic('MY_USERNAME', 'MY_PASSWORD')


.header('Accept', ContentType.JSON.getAcceptHeader())


.contentType(ContentType.JSON)


.body(validRequest)


.post(path)


.then().extract().response();
Assertions.assertEquals(201, createUser.getStatusCode());

String username = createUser.jsonPath().get('username');
String email = createUser.jsonPath().get('email');
String name = createUser.jsonPath().get('name');
String id = createUser.jsonPath().get('id');

Assertions.assertEquals('test-api-user', username);
Assertions.assertEquals('test-api-user@email.com', email);
Assertions.assertEquals('Test Api-User', name);
Assertions.assertNotNull(id);
} }

Tes ing ndhuwur bisa mbukak langsung saka kelas amarga bisa ditindakake dening JUnit.

Sing setConfig() cara mranata prasyarat. Cara tes nindakake tumindak (ngirim panjaluk) banjur negesake kode tanggepan lan muatan tanggepan.

Sabanjure, kita bakal nemokake babagan cara nyelehake lapisan timun ing ndhuwur tes api sing dijamin REST ing ndhuwur.




Tes API Timun lan REST

Babagan sing kudu dilakoni yaiku nambah katergantungan timun ing proyek kasebut.

Nggunakake Gradle, ing build.gradle file, iki dilebokake ing ngisor dependencies:

dependencies {
testCompile 'io.cucumber:cucumber-java:6.2.2'
testCompile 'io.cucumber:cucumber-junit:6.2.2'
testCompile 'io.rest-assured:rest-assured:3.3.0'
testCompile 'com.jayway.jsonpath:json-path:2.4.0' }

Lan iki miturut configuration ing build.gradle file:

configurations {
cucumberRuntime {
extendsFrom testImplementation
} }

Kita uga kudu nggawe tugas ing build.gradle file kanggo mbukak file fitur timun sing ngemot skenario:


task cucumber() {
dependsOn assemble, compileTestJava
doLast {
mkdir 'build/test-results/'
javaexec {

main = 'io.cucumber.core.cli.Main'

classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output

args = ['--plugin', 'pretty', '--plugin', 'html:build/test-results/functional.html', '--plugin', 'junit:build/test-results/functional.xml','--tags', '@functional', '--glue', 'scenarios', 'src/test/resources']
}
} }

Struktur Proyek kanggo Timun

Kita uga kudu ngowahi struktur proyek kanggo nampung pangowahan timun.

File fitur bakal disimpen ing:

src/test/resources/scenarios

Definisi langkah kasebut bakal disimpen


src/test/java/scenarios

Sabanjure, kita bakal nggawe file fitur sing diarani UserScenarios.feature lan lebokna ing sangisore src/test/resources/scenarios folder.

File fitur bakal katon kaya:

@functional Feature: User Scenarios Scenario: I should be able to create a new user
Given the users endpoint exists
When I send a valid create user payload
Then response status code should be 201
And create user response should be valid

Saiki kita kudu ngilangi tes JUnit sing JAMINAN kanggo nulis definisi langkah sing bisa ditempelake ing pernyataan ing file fitur kita.


import io.cucumber.java.en.And; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; import org.junit.jupiter.api.Assertions; import static io.restassured.RestAssured.given; public class UserScenarios {
private String path;
private Response response;
private String validRequest = '{ ' +

' 'username': 'test-api-user', ' +

' 'email': 'test-api-user@email.com', ' +

' 'password': 'Passw0rd123!', ' +

' 'name': 'Test Api-User' }';
@Given('the users endpoint exists')
public void preReq() {
RestAssured.baseURI = 'https://localhost:8080';
path = '/users';
}
@When('I send a valid create user payload')
public void createUser() {
response = given()


.auth()


.preemptive()


.basic('MY_USERNAME', 'MY_PASSWORD')


.header('Accept', ContentType.JSON.getAcceptHeader())


.contentType(ContentType.JSON)


.body(validRequest)


.post(path)


.then().extract().response();
}
@Then('response status code should be {int}')
public void checkResponseStatusCode(int code) {
Assertions.assertEquals(code, response.getStatusCode());
}
@And('create user response should be valid')
public void verifyResponse() {
String username = response.jsonPath().get('username');
String email = response.jsonPath().get('email');
String name = response.jsonPath().get('name');
String id = response.jsonPath().get('id');

Assertions.assertEquals('test-api-user', username);
Assertions.assertEquals('test-api-user@email.com', email);
Assertions.assertEquals('Test Api-User', name);
Assertions.assertNotNull(id);
} }

Kaya sing bisa dideleng ing definisi langkah ing ndhuwur, kanggo saben baris ing skenario ing file fitur, kita duwe definisi langkah sing cocog.

Cara nganggo Given anotasi mranata prasyarat. Cara nganggo When anotasi yaiku tumindak ngirim panjaluk lan pungkasane cara nganggo Then anotasi nindakake pratelan ing respon.

Kanggo nglakokake perkara ing ndhuwur, sing kudu dilakoni yaiku nglakokake prentah ./gradle cucumber ing terminal saka root project.

Sawise tes mlaku, asile disimpen ing build/test-results/functional.html.



Kesimpulan

Ing kiriman iki, kita nutupi pandhuan langkah-langkah babagan cara nambah lapisan timun ing ndhuwur tes API sing REST. Kanthi mangkono, kita bisa nulis skenario ing file fitur sing dadi luwih bisa diwaca dening wong sing dudu teknis.