Selenium - Cara mulihake cookie ing Jendhela Browser Anyar

Upamane kita kudu nyoba skenario ing ngisor iki:

1. Bukak kaca login lan mlebu aplikasi
2. Tutup browser
3. Bukak browser banjur bukak kaca login - pangguna ngirim ora ndeleng formulir mlebu lan kudu wis log in.

Ing mlebu pisanan, cookie disimpen ing browser. Ing WebDriver, nalika jendhela browser ditutup, kabeh data sesi lan cookie bakal ilang, mula uji coba skenario ing ndhuwur ora bisa ditindakake.


Untunge, WebDriver duwe fungsi kanggo maca cookie saka browser sadurunge ditutup banjur mulihake cookie ing jendela browser anyar.

import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import java.util.Set; public class CookieTest {
WebDriver driver;
@Test
public void login_state_should_be_restored() {
driver = new FirefoxDriver();

driver.get('http://www.example.com/login');
driver.findElement(By.id('username')).sendKeys('admin');
driver.findElement(By.id('password')).sendKeys('12345');
driver.findElement(By.id('login')).click();

Assert.assertTrue(


driver.findElement(By.id('welcome')).isDisplayed());

//Before closing the browser, read the cookies
Set allCookies = driver.manage().getCookies();

driver.close();

//open a new browser window
driver = new FirefoxDriver();

//restore all cookies from previous session
for(Cookie cookie : allCookies) {

driver.manage().addCookie(cookie);
}

driver.get('http://www.example.com/login'); //Login page should not be disaplyed
Assert.assertTrue(


driver.findElement(By.id('welcome')).isDisplayed());

driver.close();
} }