How to do it
1)Create your Script to test a LogIn application using the 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 a parameter.
package automationFramework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class MultiBrowser {
public WebDriver driver;
@Parameters("browser")
@BeforeClass
// Passing Browser parameter from TestNG xml
public void before the test(String browser) {
// If the browser is Firefox, then do this
if(browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
// If the browser is IE, then do this
}else if (browser.equalsIgnoreCase("ie")) {
// Here I am setting up the path for my iedriver
System.setProperty("webdriver.ie.driver", "D:\ToolsQA\OnlineStore\drivers\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
// Doesn't the browser type, launch the Website
driver.get("http://www.store.demoqa.com");
}
// Once Before a method is completed, the Test method will start
@Test public void login() throws InterruptedException {
driver.findElement(By.xpath(".//*[@id='account']/a")).click();
driver.findElement(By.id("log")).sendKeys("testuser_1");
driver.findElement(By.id("pwd")).sendKeys("Test@123");
driver.findElement(By.id("login")).click();
}
@AfterClass public void afterTest() {
driver.quit();
}
}
3) Create a TestNG XML for running your test. Configure the TestNG XML for passing parameters i.e. to tell which browser should be used for Running the Test.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="none">
<test name="FirefoxTest">
<parameter name="browser" value="firefox" />
<classes>
<class name="automationFramework.MultiBrowser" />
</classes>
</test>
<test name="IETest">
<parameter name="browser" value="ie" />
<classes>
<class name="automationFramework.MultiBrowser" />
</classes>
</test>
</suite>
Note: You can set any number of Browsers here and just for the example purpose I have set up only two main browsers.
4) Now it’s time to run the XML. Run the test by right click on the testng.xml file and select Run As > TestNG Suite.
Note: TestNg will execute the test one by one. You may like to perform parallel tests, the next topic will cover that.