Road to verify css properties value using Webdriver

To get css values of any locator, we will create java script function with the use of “getDefaultComputedStyle”function. We will execute java script function using webdriver and fetch css properties value.
getDefaultComputedStyle () gives  default computed value of all css properties of an element.
Here I have created a sample example in which I am verifying Google home page menu bar css properties color, height and width.

package com.test;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;

public class WebdriverCSSValue {

   private WebDriver driver;
   private String baseUrl;

   @BeforeSuite
   public void setUp() throws Exception {
         driver = new FirefoxDriver();                    
         baseUrl = "https://www.google.co.in/";
         driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
   }

   @Test
   public void testCSSvalueVerifying() {
         driver.get(baseUrl + "/");
              
         // js scripts
         String js = "return window.document.defaultView.getComputedStyle(" +
                                       "window.document.getElementById('gbx3'))";
         String jsColor = js+".getPropertyValue('color')";
         String jsHeight = js+".getPropertyValue('height')";
         String jswidth = js+".getPropertyValue('width')";

         // execution of js scripts to fetch css values
         JavascriptExecutor jsexecuter = (JavascriptExecutor) driver;
         String color = (String) jsexecuter.executeScript(jsColor);
         String height = (String) jsexecuter.executeScript(jsHeight);
         String width = (String) jsexecuter.executeScript(jswidth);
              
         //assertion
         Assert.assertTrue(color.equals("rgb(34, 34, 34)"));
         Assert.assertTrue(width.equals("986px"));
         Assert.assertTrue(height.equals("29px"));
              
         // print css values
         System.out.println(color);
         System.out.println(height);
         System.out.println(width);
   }
  
   @AfterSuite
   public void tearDown() throws Exception {
         driver.quit();
  }

1 comment:

  1. @ String jsColor = js+".getPropertyValue('color')";

    I get error as Not yet implemented. Why so?

    ReplyDelete

Leave your comments, queries, suggestion I will try to provide solution