Osbarr feumaidh sinn deuchainn a dhèanamh airson an t-suidheachadh a leanas:
1. Rach gu duilleag logadh a-steach agus log a-steach don tagradh
2. Dùin am brabhsair
3. Fosgail am brabhsair agus rach chun duilleag logadh a-steach - cha bu chòir don neach-cleachdaidh am foirm logadh a-steach fhaicinn agus bu chòir a bhith air logadh a-steach mu thràth.
Air a ’chiad logadh a-steach, tha briosgaidean air an stòradh sa bhrobhsair. Ann an WebDriver, nuair a tha uinneag a ’bhrobhsair dùinte, thèid a h-uile dàta seisean agus briosgaidean a dhubhadh às, agus mar sin tha e do-dhèanta deuchainn a dhèanamh air an t-suidheachadh gu h-àrd.
Gu fortanach, tha comas aig WebDriver na briosgaidean bhon bhrobhsair a leughadh mus dùin e agus an uairsin na briosgaidean a thoirt air ais ann an uinneag ùr a ’bhrobhsair.
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();
} }