[Selenium+Java] Handling AJAX Call in Selenium Webdriver

Original URL: https://www.guru99.com/handling-ajax-call-selenium-webdriver.html

Handling AJAX Call in Selenium Webdriver

Ajax is a technique used for creating fast and dynamic web pages. This technique is asynchronous and uses a combination of Javascript and XML .

It will updates the part/s of a web page without reloading the whole page.

Some of the famous applications that uses AJAX technique are Gmail, Google Maps, Facebook, Youtube, etc.

In this tutorial, you will learn-

What is Ajax

AJAX stands for Asynchronous JavaScript & XML, and it allows the Web page to retrieve small amounts of data from the server without reloading the entire page.

For example, when you click on submit button,JavaScriptwill make a request to the server, interpret the result and update the current screen without reloading the webpage.

  • An Ajax call is an asynchronous request initiated by the browser that does not directly result in a page transition. It means, if you fire an Ajax request, the user can still work on the application while the request is waiting for a response.
  • AJAX sends HTTP requests from the client to server and then process the server‘s response, without reloading the entire page. So when you make an AJAX call, you are not pretty sure about the time taken by the server to send you a response.

From a tester‘s point of view, if you are checking the content or the element to be displayed , you need to wait till you get the response. During AJAX call the data is stored in XML format and retrieved from the server.

How to handle Ajax call Using Selenium Webdriver

The biggest challenge in handling Ajax call is knowing the loading time for the web page. Since the loading of the web page will last only for a fraction of seconds, it is difficult for the tester to test such application through automation tool. For that, Selenium Webdriver has to use the wait method on this Ajax Call.

So by executing this wait command, selenium will suspend the execution of currentTest Caseand wait for the expected or new value. When the new value or field appears, the suspended test cases will get executed by Selenium Webdriver.

Following are the wait methods that Selenium Webdriver can use

  1. Thread.Sleep()
  • Thread.Sleep () is not a wise choice as it suspends the current thread for the specified amount of time.
  • In AJAX, you can never be sure about the exact wait time. So, your test will fail if the element won‘t show up within the wait time. Moreover, it increases the overhead because calling Thread.sleep(t) makes the current thread to be moved from the running queue to the waiting queue.
  • After the time ‘t‘ reached, the current thread will move from the waiting queue to the ready queue, and then it takes some time to be picked by the CPU and be running.
  1. Implicit Wait()
  • This method tells webdriver to wait if the element is not available immediately, but this wait will be in place for the entire time the browser is open. So any search for the elements on the page could take the time the implicit wait is set for.
  1. Explicit Wait()
  • Explicit wait is used to freeze the test execution till the time a particular condition is met or maximum time lapses.
  1. WebdriverWait
  • It can be used for any conditions. This can be achieved with WebDriverWait in combination with ExpectedCondition
  • The best way to wait for an element dynamically is checking for the condition every second and continuing to the next command in the script as soon as the condition is met.

But the problem with all these waits is, you have to mention the time out unit. What if the element is still not present within the time? So there is one more wait called Fluent wait.

  1. Fluent Wait
  • This is an implementation of the Wait interface having its timeout and polling interval. Each FluentWait instance determines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.

Challenges in Handling Ajax Call in Selenium Webdriver

  • Using "pause" command for handling Ajax call is not completely reliable. Long pause time makes the test unacceptably slow and increases theTestingtime. Instead, "waitforcondition" will be more helpful in testing Ajax applications.
  • It is difficult to assess the risk associated with particular Ajax applications
  • Given full freedom to developers to modify Ajax application makes the testing process challenging
  • Creating automated test request may be difficult for testing tools as such AJAX application often use different encoding or serialization technique to submit POST data.

An Example for Ajax HANDLING

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Ajaxdemo {

	private String URL = "http://demo.guru99.com/test/ajax.html";

	WebDriver driver;
	WebDriverWait wait;

	@BeforeClass
	public void setUp() {
		System.setProperty("webdriver.chrome.driver",".\\chromedriver.exe");
		//create chrome instance
		driver = new ChromeDriver();
		driver.manage().window().maximize();
		driver.navigate().to(URL);
	}

	@Test
	public void test_AjaxExample() {

		By container = By.cssSelector(".container");
		wait = new WebDriverWait(driver, 5);
		wait.until(ExpectedConditions.presenceOfElementLocated(container));

		//Get the text before performing an ajax call
		WebElement noTextElement = driver.findElement(By.className("radiobutton"));
		String textBefore = noTextElement.getText().trim();

		//Click on the radio button
		driver.findElement(By.id("yes")).click();

		//Click on Check Button
		driver.findElement(By.id("buttoncheck")).click();

		/*Get the text after ajax call*/
		WebElement TextElement = driver.findElement(By.className("radiobutton"));
		wait.until(ExpectedConditions.visibilityOf(TextElement));
		String textAfter = TextElement.getText().trim();

		/*Verify both texts before ajax call and after ajax call text.*/
		Assert.assertNotEquals(textBefore, textAfter);
		System.out.println("Ajax Call Performed");

		String expectedText = "Radio button is checked and it‘s value is Yes";

		/*Verify expected text with text updated after ajax call*/
		Assert.assertEquals(textAfter, expectedText);
		driver.close();
	}

}

Summary:

  • AJAX allows the Web page to retrieve small amounts of data from the server without reloading the entire page.
  • To test Ajax application, different wait methods should be applied
    • ThreadSleep
    • Implicit Wait
    • Explicit Wait
    • WebdriverWait
    • Fluent Wait
  • Creating automated test request may be difficult for testing tools as such AJAX application often use different encoding or serialization technique to submit POST data.

原文地址:https://www.cnblogs.com/alicegu2009/p/9098699.html

时间: 2024-07-30 20:36:05

[Selenium+Java] Handling AJAX Call in Selenium Webdriver的相关文章

[Selenium+Java] Cross Browser Testing using Selenium WebDriver

Original URL: https://www.guru99.com/cross-browser-testing-using-selenium.html What is Cross Browser Testing? Cross Browser Testing is a type of functional test to check that your web application works as expected in different browsers. Why do we nee

软件测试之Selenium Java WebDriver

编写Selenium Java WebDriver程序,测试inputgit.csv表格中的学号和git地址的对应关系 package selenium2; import java.util.regex.Pattern; import java.util.concurrent.TimeUnit; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import o

Selenium Java WebDriver 使用

一. Firefox安装Selenium插件 在FireFox的菜单中的附加组件中搜索Selenium IDE 然后安装 二. 使用Selenium IDE录制脚本/导出脚本 点击图中标志打开Selenium IDE 红色按钮按下表示正在录制,这时候只用将界面切换到Firefox,网址中输入www.baidu.com,然后再搜索框中输入文字,点击搜索,所有的控件的访问都会被记录下来,然后切换回seleniumIDE就可以看到已经录制完毕 然后在图中红色选中的区域可以调整重新执行的速度,蓝色选中区

Quick solution to java.lang.NoClassDefFoundError: org/openqa/selenium/HasInputDevices error

In case if you face this problem, one of the possible solutions that will work for you is to make sure that your pom.xml file is up to date and you use right version of webdriver and selenium java bindings. Here's what helped me <dependency> <gro

Selenium Web 自动化 - Selenium(Java)环境搭建

Selenium Web 自动化 - Selenium(Java)环境搭建 2016-07-29 第1章 Selenium环境搭建 1.1 下载JDK JDK下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 1.2 安装和配置JDK 安装目录尽量不要有空格  D:\Java\jdk1.8.0_91; D:\Java\jre8 设置环境变量: “我的电脑”->右键->“

selenium + java + testNG 自动化环境搭建

kSelenium终极自动化测试环境搭建(一)Selenium+Eclipse+Junit+TestNG 第一步 安装JDK JDk1.7. 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html 一路猛击'下一步',OK.安装完成后配置环境变量: JAVA_HOME = E:\Java\Java\jdk1.7.0_15 PATH = %JAVA_HOME%\bin CLAS

selenium+java的常使用的一些操作

常用操作均在下面的有测试用例有体现. 1 package CRM; 2 3 import static org.testng.Assert.assertEquals; 4 5 import java.awt.Checkbox; 6 import java.sql.Driver; 7 import java.util.Iterator; 8 import java.util.List; 9 import java.util.Set; 10 import java.util.concurrent.D

Selenium+Java 浏览器操作(一)

1.获取当前url和title /*获取当前url和title*/ System.out.println("URL="+dr.getCurrentUrl()); //获取当前url System.out.println("title="+dr.getTitle()); //获取当前页面title 2.浏览器的前进,后退,刷新,跳转链接 package selenium; import java.util.Set; import java.util.concurren

自动化测试【Maven+Eclipse+Selenium+Java环境搭建和测试】

一.下载必要的文件 1.eclipse Eclipse官网 2.jdk jdk官网 3.selenium IDE.Selenium Server.Selenium Client Drivers(Java)等等 Selenium下载地址  备注:需要代理服务器才能下载 我使用的是太太猫 4.maven安装.配置等 二.安装    1.Eclipse解压缩就可以用了    2.jdk安装.配置变量等    3.Selenium相关的安装    4.maven 最新版本的Eclipse已经自带mave