In this post, we will see how does one make use of TestNG to kick off parallel UI tests using WebDriver.

So lets try doing this with a typical cooking recipe style :)

So here are the ingredients that are required.

  • A Factory class that will create WebDriver instances
  • A Manager class that can be accessed to retrieve a WebDriver instance
  • A TestNG listener that will be responsible for instantiating the WebDriver instance automatically

So without wasting any time lets see how this all blends in.

First lets look at our Factory class. This is a very simplified Factory class that will create instances of WebDriver based upon the browser flavour. I have purposefully kept it simple only for illustration purposes:
Here’s how the Factory class will look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package organized.chaos;
 
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
 
class LocalDriverFactory {
    static WebDriver createInstance(String browserName) {
        WebDriver driver = null;
        if (browserName.toLowerCase().contains("firefox")) {
            driver = new FirefoxDriver();
            return driver;
        }
        if (browserName.toLowerCase().contains("internet")) {
            driver = new InternetExplorerDriver();
            return driver;
        }
        if (browserName.toLowerCase().contains("chrome")) {
            driver = new ChromeDriver();
            return driver;
        }
        return driver;
    }
}

As you can see its a very simple class with a static method that creates WebDriver instances. The one interesting part to be noted here is that the class has been purposefully given only package visibility [ notice how the keyword "public" is missing from the class declaration ]. One of the many aspects that are involved in designing APIs is “Hide what is not necessary to be visible to your user”. For you to be able to drive a car, you don’t need to know how the piston works or how the fuel injection happens do you :)

Now lets take a look at how our Manager class would look like. The Manager class essentially uses a concept in java called ThreadLocalvariables.

The code would look like below :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package organized.chaos;
 
import org.openqa.selenium.WebDriver;
 
public class LocalDriverManager {
    private static ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
 
    public static WebDriver getDriver() {
        return webDriver.get();
    }
 
    static void setWebDriver(WebDriver driver) {
        webDriver.set(driver);
    }
}

Were you surprised that its such a small class ? :)
So as you can see we basically have a static ThreadLocal variable wherein we are setting webDriver instances and also querying webdriver instances as well.

Next comes the TestNG listener. The role of the TestNG listener is to perform “Automatic webdriver instantiation” behind the scenes without your test code even realising it. For this we will make use of IInvokedMethodListener so that the WebDriver gets instantiated right before a Test Method gets invoked and the webDriver gets automatically quit right after the Test method.
You can improvize this by incorporating custom annotations as well and parsing for your custom annotations [ The current implementation that you will see basically spawns a browser irrespective of whether you want to use it or not. That's not a nice idea all the time is it ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package organized.chaos;
 
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
 
public class WebDriverListener implements IInvokedMethodListener {
 
    @Override
    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
        if (method.isTestMethod()) {
            String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
            WebDriver driver = LocalDriverFactory.createInstance(browserName);
            LocalDriverManager.setWebDriver(driver);
        }
    }
 
    @Override
    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
        if (method.isTestMethod()) {
            WebDriver driver = LocalDriverManager.getDriver();
            if (driver != null) {
                driver.quit();
            }
        }
    }
}

Now that we have shown all of the ingredients, lets take a look at a sample test as well, which is going to use all of this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package organized.chaos;
 
import org.testng.annotations.Test;
 
public class ThreadLocalDemo {
    @Test
    public void testMethod1() {
        invokeBrowser("http://www.ndtv.com");
    }
 
    @Test
    public void testMethod2() {
        invokeBrowser("http://www.facebook.com");
 
    }
 
    private void invokeBrowser(String url) {
        System.out.println("Thread id = " + Thread.currentThread().getId());
        System.out.println("Hashcode of webDriver instance = " + LocalDriverManager.getDriver().hashCode());
        LocalDriverManager.getDriver().get(url);
 
    }
}

As you can see its a very simple test class with two test methods. Each of the test methods opens up a different website. I have also add print statements for printing the thread id [yes thats the only reliable way of figuring out if your test method is running in parallel or in sequential mode. If you see unique values for Thread.currentThread().getId() then you can rest assured that TestNG is invoking your test methods in parallel.
We are printing the hashCode() values for the browser to demonstrate the fact that there are unique and different webDriver instances being created for every test method. [ Remember hashCode() value for an object would always be unique ]

Now lets take a look at how our suite file looks like :

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="methods">
<listeners>
<listener class-name="organized.chaos.WebDriverListener"></listener>
</listeners>
    <test name="Test">
        <parameter name="browserName" value="firefox"></parameter>
        <classes>
            <class name="organized.chaos.ThreadLocalDemo" />
        </classes>
    </test> <!-- Test -->
</suite> <!-- Suite -->

So when you run this test this is how your output would look like [ apart from you seeing two firefox windows popup on your desktop ]

1
2
3
4
5
6
7
8
9
10
11
12
[TestNG] Running:
  /githome/PlayGround/testbed/src/test/resources/threadLocalDem.xml
 
Thread id = 10
Hashcode of webDriver instance = 1921042184
Thread id = 9
Hashcode of webDriver instance = 2017986718
 
===============================================
Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================

And thus we have managed to leverage TestNG and run WebDriver tests in parallel without having to worry about race conditions or leaving browsers open etc.,

Hope that clears out some of the confusions and helps you get started with WebDriver automation powered by TestNG.

Parallel WebDriver executions using TestNG的更多相关文章

  1. Selenium2(webdriver)入门之TestNG的使用

    一.在Eclipse中安装TestNG 1.打开eclipse-->help-->Install New Software-->Add,输入Name和Location后,点击OK. ...

  2. Selenium2(webdriver)入门之TestNG的安装与简单使用

    上一篇已经搭建好了Eclipse+selenium2的环境,这一篇主要记录下TestNG的使用. 一.在Eclipse中安装TestNG 1.打开eclipse-->help-->Inst ...

  3. 基于WebDriver&TestNG 实现自己的Annotation @TakeScreenshotOnFailure

    相信用过Selenium WebDriver 的朋友都应该知道如何使用WebDriver API实现Take Screenshot的功能. 在这篇文章里,我主要来介绍对failed tests实现 t ...

  4. testng 失败自动截图

    testng执行case failed ,testng Listener会捕获执行失败,如果要实现失败自动截图,需要重写Listener的onTestFailure方法 那么首先新建一个Listene ...

  5. WebDriver - 添加失败截图

    WebDriver失败截图可以通过两种方式实现: 1. Use WebdriverEventListener 第一步:创建自己的WebDriverEventListener 创建自己的WebDrive ...

  6. TestNG实现日志输出

    这里介绍的是TestNG中的Report类来实现简单的log输出这个很简单直接看例子吧 package com.rrx.test; import java.io.IOException; import ...

  7. TestNG实现用例运行失败自动截图(转载)

    转载自:https://blog.csdn.net/galen2016/article/details/70193684 重写Listener的onTestFailure方法 package com. ...

  8. testng失败截图,注解方式调用。

    今天一整天都在研究testng失败截图的方法,参考网上的前辈们的资料,加上自己的理解,终于搞出来了. package com.dengnapianhuahai; /** * 自定义注释 * */ im ...

  9. maven+selenium+java+testng+jenkins自动化测试

    最近在公司搭建了一套基于maven+selenium+java+testng+jenkins的自动化测试框架,免得以后重写记录下 工程目录 pom.xml <project xmlns=&quo ...

随机推荐

  1. SQL Server 2008安装和配置过程

    下面我将用图解的方式,来介绍SQL Server 2008安装和配置过程,希望对大家有所帮助. 闲言少叙,直奔主题!点击setup.exe安装文件后,如果系统没有以下组件,则会出现如下提示! 安装20 ...

  2. Memcache+Tomcat9集群实现session共享(非jar式配置, 手动编写Memcache客户端)

    Windows上两个tomcat, 虚拟机中ip为192.168.0.30的centos上一个(测试用三台就够了, 为了测试看见端口所以没有使用nginx转发请求) 开始 1.windows上开启两个 ...

  3. DOM文档对象总结

    DOM总结: DOM:文档对象模型document object model DOM三层模型: DOM1:将HTML文档封装成对象 DOM2:将XML文档封装成对象 DOM3:将XML文档封装成对象 ...

  4. HTTP 错误 500.21 - Internal Server ErrorHTTP

    应用程序“DEFAULT WEB SITE/WINDRP_TB/TBFXWS”中的服务器错误Internet Information Services 7.5错误摘要HTTP 错误 500.21 - ...

  5. Getting Started with Java

    “学前”说明:<Learn Java for Android>这本书内容很多,都是精华,建议大家看英文版的.在这里我不打算一一总结书中的内容,书中每章节后面的exercises都很好,非常 ...

  6. Ffmpeg 定位文件(seek file)

    有朋友问到ffmpeg播放文件如何定位问题,我想到应该还有一些新手朋友对这一块比较陌生.ffmpeg定位问题用到seek方法,代码 如下: void SeekFrame(AVFormatContext ...

  7. 2186: [Sdoi2008]沙拉公主的困惑 - BZOJ

    Description 大富翁国因为通货膨胀,以及假钞泛滥,政府决定推出一项新的政策:现有钞票编号范围为1到N的阶乘,但是,政府只发行编号与M!互质的钞票.房地产第一大户沙拉公主决定预测一下大富翁国现 ...

  8. ORA-01031:insufficient privileges

    描述:oracle11g用scott用户在plsql上以sysdba身份登录显示以上错误,可是在cmd面板中却正常,网上各种找答案不没有对症,最后这位网友的回答解决了我的问题. 原帖网址:http:/ ...

  9. 有关javascript中的JSON.parse和JSON.stringify的使用一二

    有没有想过,当我们的大后台只是扮演一个数据库的角色,json在前后台的数据交换中扮演极其重要的角色时,作为依托node的前端开发,其实相当多的时间都是在处理数据,准确地说就是在处理逻辑和数据(这周实习 ...

  10. Eclipse plugin插件开发 NoClassDefFoundError

    Eclipse的每一个plugin都有属于自己的类加载器,这是OSGI架构的基础,每一个plugin项目都是一个bundle,独立运行在各自的运行环境里面,这就造成了开发时和运行时的不同. Eclip ...