Selenium 简明教程

Selenium Webdriver - Cross Browser Testing

在 Selenium Webdriver 中开发的测试用例应能够在多个浏览器(如 Chrome、Firefox、Safari、Edge 等)中运行,只需对测试用例进行微小的更新。这有助于检查被测应用程序是否在所有浏览器中按要求工作。

The test case developed in Selenium Webdriver should be able to run in multiple browsers like Chrome, Firefox, Safari, Edge, and so on with minor updates to the test case. This helps to check if the application under test is working as per the requirements in all the browsers.

Why is Cross Browser Testing Beneficial?

通常在处理任何应用程序(例如电子商务或旅行预订等)的过程中,我们会注意到在付款或向购物车中添加产品时,应用程序在特定浏览器中花费太多时间加载页面。

Often on working on any applications for example, e-commerce or on travel reservations, and so on, we observe that while doing the payment, or adding products to cart, the applications are taking too much time for page load on a specific browser.

作为用户,我们可以立即推断出该应用程序可能存在错误或正在出现问题,然后我们转向具有类似产品和功能的其他公司网站。

As a user, we promptly infer that there may be an error or an ongoing issue in that application, and we move towards a different company website having the similar products and functionalities.

尽管浏览器供应商基于开放 Web 标准,但基于 JavaScript、HTML 和 CSS 构建的 Web 应用程序和应用呈现方式不同。这导致应用程序在不同浏览器中呈现不同。任何应用程序的源代码调试无法洞察其如何在不同浏览器中呈现。

The web application and apps built on JavaScript, HTML, and CSS render dissimilarly, in spite of the fact browser vendors are based on the Open Web Standards. This results in representation of applications different in different browsers. The source code debugging of any application does not give any insight on how it will be represented in different browsers.

因此,跨浏览器测试对于尽早检测任何应用程序在任何浏览器中的兼容性问题很有好处,以便它可以广泛用于各种用户,而不仅仅是任何目标用户组。此外,在执行跨浏览器自动化测试时,我们最终可能会使用并行执行创建测试套件,这将帮助我们扩大测试规模。

Thus cross browser testing is beneficial to detect compatibility issues of any application in any browser earlier so that it can be used widely for all kinds of users rather than any targeted user group. Also, while doing automated cross browser testing, we may end up creating a test suite with parallel execution, which will help us to scale up the test.

跨浏览器测试确保无论浏览器或操作系统如何,应用程序构建都可以平稳使用,并能很好地参与用户交互。

The cross browser testing ensures that which has been application built can be used smoothly with a nice user participation irrespective of any browsers or operating systems.

Example

让我们以上述页面为例,我们在此页面上的 New User button 中有 Welcome Page

Let us take an example of the below page, where we have the New User button on the Welcome Page.

selenium cross browser 1

单击 New User 按钮时,我们将导航到注册页面,其中包含 Welcome, Register 文本,如下面的图像所示。

On clicking the New User button, we will be navigating to the Registration page, having the Welcome, Register text as shown in the below image.

selenium cross browser 2

对于上述示例,我们将在 Chrome 和 Edge 浏览器中对上述功能进行跨浏览器测试。为了在同一本地系统中的两个浏览器中同时运行测试,我们将借助 TestNg 单元测试自动化框架。所有测试用例都将位于同一 CrossBrw 包下。我们将通过在测试类 BrowserTest.java 中使用 @Parameters 标签传递值并在 testng.xml 文件中指定 parameter = browser 及其 value = Chromevalue = Edge 在两个浏览器中运行测试。

For the above example, we would do a cross browser testing of the above functionalities in Chrome, and Edge browsers. In order to run the tests simultaneously in two browsers in the same local system, we would take the help of TestNg unit test automation framework. All the test cases would be under the same CrossBrw package. We would run the test in both the browsers by passing the values using the @Parameters tag in the test class BrowserTest.java and specified the parameter = browser and its value = Chrome, and value = Edge in the testng.xml file.

selenium cross browser 3

测试类 BrowserTest.java 中的代码实现。

Code Implementation on test class BrowserTest.java.

package CrossBrw;

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.edge.EdgeDriver;
import org.testng.annotations.*;
import java.util.concurrent.TimeUnit;

public class BrowserTest {
   WebDriver driver;
   @BeforeTest
   @Parameters("browser")
   public void setup(String browser) throws Exception{

      // Initiate browser driver as per browser value
      if (browser.equalsIgnoreCase("Chrome")) {
         driver = new ChromeDriver();
         System.out.println("Browser opened in Chrome");
      } else if (browser.equalsIgnoreCase("Edge")) {
         driver = new EdgeDriver();
         System.out.println("Browser opened in Edge");
      }

      // adding implicit wait of 12 secs
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      // Opening the webpage
      driver.get("https://www.tutorialspoint.com/selenium/practice/login.php");
   }

   @Test(priority = 1)
   public void verifyWelcomePageHeading() {
      WebElement t = driver.findElement(By.xpath("//*[@id='signInForm']/h1"));
      System.out.println("Page heading in Welcome Page: " +  t.getText());
   }

   @Test(priority = 2)
   public void moveToRegisterPage() {
      WebElement btn = driver.findElement(By.xpath("//*[@id='signInForm']/div[3]/a"));
      btn.click();
   }

   @Test(priority = 3)
   public void verifyRegisterPageHeading() {
      WebElement t = driver.findElement(By.xpath("//*[@id='signupForm']/h1"));
      System.out.println("Page heading in Register Page: " + t.getText());
   }

   @AfterTest
   public void teardown() {

      // quitting browser
      driver.quit();
   }
}

testng.xml 中的配置。

Configurations in testng.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="All Test Suite" thread-count="5" parallel="tests">
   <test thread-count="5" name="ChromeTest">
      <parameter name="browser" value="Chrome"></parameter>
      <classes>
         <class name="CrossBrw.BrowserTest"/>
      </classes>
   </test> <!-- Test -->
   <test thread-count="5" name="EdgeTest">
      <parameter name="browser" value="Edge"></parameter>
      <classes>
         <class name="CrossBrw.BrowserTest"/>
      </classes>
   </test>
</suite>

pom.xml 中的依赖项。

Dependencies in pom.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>

   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.testng/testng -->
      <dependency>
         <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <version>7.9.0</version>
         <scope>test</scope>
      </dependency>
   </dependencies>
</project>

我们需要右键单击 testng.xml 文件并选择运行 testng.xml 选项,从 testng.xml 文件运行测试。

We would need to run the test from the testng.xml file, by right clicking on it, and selecting the option Run testng.xml.

Output

Browser opened in Chrome
Browser opened in Edge
Page heading in Welcome Page: Welcome, Login In
Page heading in Register Page: Welcome,Register
Page heading in Welcome Page: Welcome, Login In
Page heading in Register Page: Welcome,Register
===============================================
All Test Suite
Total tests run: 6, Passes: 6, Failures: 0, Skips: 0
===============================================

Process finished with exit code 0
selenium cross browser 4

在上述示例中,我们首先在 testng.xml 文件内传递了参数 browser 及其值 ChromeEdge 。在测试类 BrowserTest.java 内,我们执行了测试方法 - verifyWelcomePageHeading()、moveToRegisterPage() 和 verifyRegisterPageHeading(),一次在 Chrome 中,然后在 Edge 中。

In the above example, we had first passed the parameter browser and its values Chrome, and Edge within the testng.xml files. Within the test class BrowserTest.java, we had executed the test methods - verifyWelcomePageHeading(), moveToRegisterPage(), and verifyRegisterPageHeading() once in Chrome, and then in Edge.

我们借助 TestNG 测试框架和 Selenium Webdriver 来实现跨浏览器测试,并在控制台中两次(一次在 Chrome 中,然后在 Edge 中)获取带有消息的页面标题 - Page heading in Welcome Page: Welcome, Login In, Page heading in Register Page: Welcome,Register, Page heading in Welcome Page: Welcome, Login In, and Page heading in Register Page: Welcome,Register 。我们还获取了在控制台中带有 @BeforeTest 注释的测试方法 setup() 的消息 - Browser opened in ChromeBrowser opened in Edge

We had taken help of the TestNG test framework along with Selenium Webdriver, to implement the cross browser testing and retrieved the page headers with the messages two times(once in Chrome, and then Edge) in the console - Page heading in Welcome Page: Welcome, Login In, Page heading in Register Page: Welcome,Register, Page heading in Welcome Page: Welcome, Login In, and Page heading in Register Page: Welcome,Register. We had also obtained the messages for the test method setup() having the @BeforeTest annotation in the console - Browser opened in Chrome, and Browser opened in Edge.

控制台中的结果显示总共运行的测试数:6,因为有三个具有 @Test 注释的方法 - verifyWelcomePageHeading()、moveToRegisterPage() 和 verifyRegisterPageHeading() 执行了两次(针对 Chrome 和 Edge)。

The result in the console shows Total tests run: 6, as there are three methods with @Test annotations - verifyWelcomePageHeading(), moveToRegisterPage(), and verifyRegisterPageHeading() were executed twice(for Chrome, and Edge).

最后,收到消息 Passes: 6Process finished with exit code 0 ,表明代码执行成功。

Finally, the message Passes: 6, and Process finished with exit code 0 was received, signifying successful execution of the code.

完成了有关 Selenium Webdriver - 跨浏览器测试教程的全面讲解。我们从跨浏览器测试是什么以及跨浏览器测试的优点开始,并通过一个示例来说明如何将跨浏览器与 Selenium 和 TestNG 结合使用。这将为您提供跨浏览器测试的深入知识。明智的做法是坚持练习您所学的内容,并探索与 Selenium 相关的其他内容,以加深您的理解并拓宽您的视野。

This concludes our comprehensive take on the tutorial on Selenium Webdriver - Cross Browser Testing. We’ve started with describing cross browser testing, and why cross browser testing is beneficial, and an example illustrating how to use a cross browser along with Selenium and TestNG. This equips you with in-depth knowledge of the cross browser testing. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.