Cara entuk Kode Status Response karo Selenium WebDriver

Kerep banget nalika mbukak kir otomatis karo Selenium WebDriver, sampeyan uga pengin mriksa kode status respons kanggo sumber, kayata layanan web utawa kaca web liyane ing situs kasebut. Sampeyan uga bisa mriksa tautan sing rusak ing situs kasebut nalika nglakokake skrip Selenium WebDriver.

Ayo maneh kode status HTTP sing beda:

2xx - OK
3xx - Pangalihan
4xx - Sumber ora ditemokake
5xx - Kesalahan server


Ing Selenium WebDriver ora ana cara langsung kanggo mriksa kode status respons, mula kita kudu nggunakake perpustakaan liyane kanggo iki. Kita bisa nggunakake Klien Apache utawa aku luwih seneng nggunakake Perpustakaan sing dijamin paling apik saka Jayway

Kanggo entuk kode respons nggunakake REST-sure kita bisa nggunakake:


import io.restassured.RestAssured; public class HttpResponseCode {
public int httpResponseCodeViaGet(String url) {

return RestAssured.get(url).statusCode();
}
public int httpResponseCodeViaPost(String url) {
return RestAssured.post(url).statusCode();
}
public static void main(String args[]) {
new HttpResponseCode().httpResponseCodeViaGet('http://www.google.com');
} }

Output:



200

Kanggo mriksa link sing rusak ing kaca kasebut nalika nglakokake tes Selenium WebDriver, kita bisa nggunakake:

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.List; public class HttpResponseCode {
WebDriver driver;
int statusCode
public void checkBrokenLinks() {
driver = new FirefoxDriver();
driver.get('https://devqa.io');

//Get all the links on the page
List links = driver.findElements(By.cssSelector('a'));

String href;

for(WebElement link : links) {

href = link.getAttribute('href');

statusCode = new HttpResponseCode().httpResponseCodeViaGet(href);

if(200 != statusCode) {


System.out.println(href + ' gave a response code of ' + statusCode);

}
}
}
public static void main(String args[]) {
new HttpResponseCode().checkBrokenLinks();
} }

Wacan luwih lanjut: