Saturday, June 28, 2014

Selenium :Headless Browser testing using HtmlUnitDriver and PhantomJS inWebdriver



Headless Browser testing using HtmlUnitDriver and PhantomJS inWebdriver

Headless Browser is a Web Browser without a GUI (Graphical User Interface). It access Web Pages but doesn't show them to any human being. Headless Browser should be able to parse JavaScript.

Html Unit Driver:

HtmlUnitDriver driver = new HtmlUnitDriver();
driver.setJavascriptEnabled(true); //to enable Javascript

To emulate a specific browser :

                   HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3);
 
The other uses a broader capabilities mechanism: 

                   HtmlUnitDriver driver = new HtmlUnitDriver(capabilities);
 
 

PhantomJS

PhantomJS is a Headless Webkit with JavaScript API. PhantomJS is an optimal solution for Headless Website Testing, Screen Capture, Access and manipulate webpages with the standard DOM API, or with usual libraries like jQuery, Network Monitoring PhantomJS comes with in-built GhostDriver.

Note : PhantomJS is not a Test framework, it is used only to LAUNCH the tests via a suitable Test Runner(GhostDriver) for webdriver.


Configure PhantomJS :
1.     PhantomJSDriver-1.0.x.jar can also be downloaded and configured in Eclipse manually.
2.     Add the following imports to your code:

import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;


3. Replace the object, "driver" specifying "FirefoxDriver" with "PhantomJSDriver".
4. Use
WebDriver driver = new PhantomJSDriver();

5. Run Test.

Note:
You can also do the following:
1. Download phantomjs.exe
2. Extract the phantomjs-1.8.x-windows.zip folder and locate phantomjs.exe file to C: / folder
-use the following code instead of the above:

DesiredCapabilities ph_cap = new DesiredCapabilities();
ph_cap.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:/phantomjs.exe");
WebDriver driver = new PhantomJSDriver(ph_cap);

PhantomJS | Screen Capture

DesiredCapabilities ph_cap  = new DesiredCapabilities();
ph_cap.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C://phantomjs.exe");
ph_cap .setCapability("takesScreenshot", true);
driver = new PhantomJSDriver(ph_cap );  
baseUrl = "http://www.xyz.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);


@Test
public void test01() throws Exception {

driver.get(baseUrl + "/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\sample.jpeg"),true);
 

}


Sources :


No comments:

Post a Comment