How do you test pages that require authentication with Selenium?


We can test pages that need authentication with Selenium. For this, we have to send the credentials of the user to the URL. Actually, we are passing both the username and password appended to the URL.

Syntax

https://username:password@URL
https://admin:admin@the-internet.herokuapp.com/basic_auth

Here, the admin is the username and password.

URL – www.the-internet.herokuapp.com/basic_auth

Let us see how to accept the authentication pop-up.

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestAuthnPopup{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String t = "admin";
      // adding username, password with URL
      String s = "https://" + t + ":" + t + "@" + "the-internet.herokuapp.com/basic_auth";
      driver.get(s);
      // identify and get text after authentication of popup
      String m = driver.findElement(By.cssSelector("p")).getText();
      System.out.println("Text after pop-up authentication: " + m);
      driver.quit();
   }
}

Output

Updated on: 28-Dec-2020

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements