Cross browser testing

Sometimes in your test automation, you may require to run your script on multiple browsers to check the browser compatibility. There may be a chances that your application may look different on different browsers, this is because browsers understand some code little differently. So this is recommended that your application should be tested on at least Firefox, Chrome and IE.

TestNG has mechanism to perform same test on different browsers in a simple and easy way. Please see the following example explaining this in details.

1) Create your Script to test a using TestNG class.

2) Pass ‘Browser Type’ as parameters using TestNG annotations to the before method of the TestNG class. This method will launch only the browser, which will be provided as parameter.

Example code:
 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

public class MultiBrowser {
 public static WebDriver driver = null;

 @Test
 public void test() {
  driver.get("www.google.com");
 }

 @Parameters("browser")
 @BeforeClass
 public WebDriver beforeClass(String browser) {

  try {
   if (browser.equalsIgnoreCase("firefox")) {
    driver = new FirefoxDriver();
   }

   else if (browser.equalsIgnoreCase("chrome")) {
    System.setProperty("webdriver.chrome.driver", "../MyProject/driver/chromedriver.exe");
    driver = new ChromeDriver();
   }

  } catch (Exception e) {
   System.out.println(e);
   return null;
  }
  return driver;
 }

 @AfterClass
 public void afterTest() {
  driver.quit();
 }
}

Create following testng.xml:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite">
   <test name="FirefoxTest">
      <parameter name="browser" value="firefox" />
      <classes>
         <class name="automationFramework.MultiBrowser" />
      </classes>
   </test>
   <test name="Chrome">
      <parameter name="browser" value="chrome" />
      <classes>
         <class name="automationFramework.MultiBrowser" />
      </classes>
   </test>
</suite>


<-- Previous || Next ->

2 comments:

  1. Please include data provider in TestNG Concepts. Others are pretty good.

    ReplyDelete
  2. PLease add more content in TestNG..

    ReplyDelete