Writing Selenium java add to cart test case

Learn how to write selenium java add to cart test case, this is real world example of testing add to cart functionality. Using Amazon shopping site, selenium script developed to navigate Todays deals page and then add item to cart and verify the shopping cart page.

If you feel this video is useful, Please share it with your friends on Facebook, twitter Google plus etc.

To keep selenium driver wait for a page to load, below is the standard example.

WebDriverWait wait = new WebDriverWait(driver, 2);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("nav-cart")));

Code developed in this tutorial provided below:

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 * @author Niranjan
 *
 */
public class AmazonTestCase {

	static ChromeDriver driver = null;
	static WebDriverWait wait = null;
	
	/**
	 * @throws java.lang.Exception
	 */
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		// Replace the path of chrome driver according to your setup
		System.setProperty("webdriver.chrome.driver", "/Users/Niranjan/My Briefcase/My Development/eclipse_learning/SeleniumLearning/lib/webdrivers/chromedriver");
		
		driver = new ChromeDriver();
	}

	/**
	 * @throws java.lang.Exception
	 */
	@Before
	public void setUp() throws Exception {
		driver.get("http://wwww.amazon.com");
	}

	@Test
	public void testAddToCart() {
		driver.get("http://wwww.amazon.com");
		driver.findElementByLinkText("Today's Deals").click();
		wait = new WebDriverWait(driver, 2);
		wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Today's Deals")));
		
		// Test
		Assert.assertTrue(driver.getTitle().equals("Gold Box Deals | Today's Deals - Amazon.com"));
		
		driver.findElementById("a-autoid-1-announce").click();
		wait = new WebDriverWait(driver, 2);
		wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("nav-cart")));
		
		driver.findElementById("nav-cart").click();
		wait = new WebDriverWait(driver, 2);
		wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("sc-active-cart")));
		
		// Test
		Assert.assertTrue(driver.getTitle().equals("Amazon.com Shopping Cart"));
	}
	
	@AfterClass
	public static void CleanUp(){
		driver.quit();
	}

}

For further reading refer Java Selenium Programming Category posts.

Learning Selenium Java add to cart test case
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *