Let’s see how we can guide selenium to automate the user actions on a web application,
As we come to know from selenium element locator strategy, selenium identifies elements (WebElement) on basis of the html tags and their attributes.
Let’s take the saucedemo as our AUT(application under test) on Chrome browser
TestCase: Verify the login with valid credentials
Steps:
- Go to the url https://www.saucedemo.com/ – verify if AUT loaded
- Click on UserName > type “standard_user“
- Click on Password > type “secret_sauce“
- Click on LOGIN button
- Verify if logged in – verify the AUT URL contains string as inventory
Code implementation
We will use maven project in intelliJ ide
Add the selenium dependencies in pom.xml
If you are new to Java, then refer here
Note – For each code line below, have comments to understand the need for that line.
Create a new Maven project “SelTest” > src > test > java > Create a new class “FirstSelTest“
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.testng.annotations.Test;import java.util.concurrent.TimeUnit;public class FirstSelTest{static WebDriver driver;@Testpublic static void Test_Login() throws InterruptedException {//Provide the Chrome driver path to send the selenium requests to browserSystem.setProperty("webdriver.chrome.driver", "/Users/sunilkumarpatro/sel/chromedriver");//Launch firefox browserdriver = new ChromeDriver();//maximize the browserdriver.manage().window().maximize();//Implicit wait, wait for at least some time (10 sec) to identify an element,// if can't find the element with in 10 sec, throw exceptiondriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);//open the url or AUTdriver.get("http://www.saucedemo.com/index.html");//Identify the Username field and type text - standard_userWebElement userName = driver.findElement(By.id("user-name"));userName.sendKeys("standard_user");//Identify the password field and type text - secret_saucedriver.findElement(By.id("password")).sendKeys("secret_sauce");//Identify the LOGIN field and clickdriver.findElement(By.id("login-button")).click();Thread.sleep(2000);if (driver.getCurrentUrl().contains("inventory")) {System.out.println("Login successful!");}Thread.sleep(2000);//Close the browser[s]driver.quit();}}
Either right click on the FirstSelTest file and run the test
or
Create a testng.xml > right click > run the file
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" ><suite name="Suite1" verbose="1" ><test name="SwagLabs" ><classes><class name="FirstSelTest" /></classes></test></suite>
For other browsers like IE and Firefox, please refer working with multiple browsers.
2 Comments