EventFiringWebDriver, WebDriverEventListener, and AbstarctWebDriverEventListener

Before getting into the sample code, lets have a look on EventFiringWebDriver, WebDriverEventListener, and AbstarctWebDriverEventListener descriptions.

  • EventFiringWebDriver is a class and wrapper around an arbitrary webdriver instance which supports registering of a WebDriverEventListener.
  • WebDriverEventListener is interface which includes list of abstract events methods and all should be implemented if we are implementing it.
  • AbstarctWebDriverEventListener is abstract class which has implemented WebDriverEventListener interface. We can extend this class if we are only interested in some events. All methods provided by this class have an empty method body.

So we can choose between EventFiringWebDriver and AbstarctWebDriverEventListener according to our needs.

Note: I have used AbstarctWebDriverEventListener class in below example.

Let’s have a look on example-

Create a class file and extends AbstarctWebDriverEventListener class-
public class WebDriverEventListenerClass extends AbstractWebDriverEventListener {
@Override
public void onException(Throwable arg0, WebDriver driver) {

File screenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShot, new File(“c:\\tmp\\exception.png”));
} catch (IOException e) {
e.printStackTrace();
}}}

Create another class file and register WebDriverEventListenerClass file as it has implemented onException event method-

public class EventFiringDriverExample {
@Test
public void Events(){
System.setProperty(“webdriver.ie.driver”, “D:/Training/IE_Driver/IEDriverServer.exe”);

WebDriver driver = new InternetExplorerDriver();

// Creating EventFiringWebDriver instance

EventFiringWebDriver eventFiringDriver= new EventFiringWebDriver(driver);

// Creating instance of eventListener, that we just defined
eventFiringDriver.register(new WebDriverEventListenerClass());

eventFiringDriver.get(“https://www.google.co.in/”);

eventFiringDriver.findElement(By.className(“nosuchelement”));

}}

Once you run ‘Events()’ method, it will open Google and search for element which is not available. In this case, method will throw WebElementNotFound exception and system will capture the screenshot and save it at “c:\\tmp\\exception.png” location..

How to generate logs with CodedUI?

Why logs? Well, it helps to debug the problem in our script. Usually logging and capturing the screenshots are not enable by default with CodedUI and to make it, we need to make some set up.

Follow the below steps to enable logging and capturing the screenshots-

1: Go to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE location and search for ‘QTAgent32_40.exe.config’ and ‘QTAgent32.exe.config’. Make sure you have edit permission for these config files.

2: Modify the value for ‘EqtTraceLevel‘:

Log

3: Add App.config file in your project and add the following code under the configuration node:

Log1

4: Add following code in CodedUITest1.cs file-

Log2

5: Now run the test.

6: Open Test Explorer and click on Output hyperlink-

Log3

7: Click on UITestActionLog.html link.

Log4

8: Now check your script logs-

Log5

Log6

Difference between @BeforeTest and @BeforeClass annotation in TestNg

Ah ha…a topic which confused me also to understand the difference between BeforeTest and BeforeClass annotation. When we read first time it looks same and then we think if it is same then why TestNg included it. So clue is, it is not same and included for two different purposes-

We will go through again with these annotations definition which is available under TestNg official site and that are-

@BeforeTest-The annotated method will be run before any test method belonging to the classes inside the tag is run.

@BeforeClass-The annotated method will be run before the first test method in the current class is invoked.

Have a look on below example-

public class FirstClass {
@BeforeTest
public void BT(){
System.out.println(“This is before test”);
}
@AfterTest
public void AT(){
System.out.println(“This is after test”);
}
@Test (priority =-20)
public void fctestmethod(){
System.out.println(“This is First Class test method.”);
}}

————————————————————————————————-

public class SecondClass {
@BeforeClass
public void BC(){
System.out.println(“This is before class”);
}
@AfterClass
public void AC(){
System.out.println(“This is after class”);
}
@Test (priority =-19)
public void sctestFirstmethod(){
System.out.println(“This is Second Class first test method.”);
}
@Test (priority =-18)
public void sctestSecondmethod(){
System.out.println(“This is Second Class second test method.”);
}}

————————————————————————————————-

————————————————————————————————-

[TestNG] Running:
D:\Training\BeforeTestndClassExample\testng.xml

This is before test
This is First Class test method.
This is before class
This is Second Class first test method.
This is Second Class second test method.
This is after class
This is after test

===============================================
My test suite
Total tests run: 3, Failures: 0, Skips: 0
===============================================

————————————————————————————————-

Hints:

  • <test> tag is wrapped by @BeforeTest and @AfterTest
  • <class> tag is wrapped by @BeforeClass and @AfterClass

So if we see in test result @BeforeTest method executed very first and then lowest priority @Test method (fctestmethod). In third position @BeforeClass method executed which was defined in Second Class. Now question is why it got executed at third position, so answer is-

  • <class> tag is wrapped by @BeforeClass and @AfterClass

and

@BeforeClass-The annotated method will be run before the first test method in the current class is invoked.

As @Before and After was defined in Second Class therefore it got executed when testng.xml invoked Second Class class file not before any test.

Logging with Log4J

Log4j is widely used API for generating the logs and there are few steps to configure it with Selenium Webdriver.

  • Download the latest log4j api from here.
  • Include the log4j-1.2.XX.jar file in your project build path.
  • Right click on your project > New > Other…>XML>XML FIle> and create a XML file with the log4j.xml name.
  • Copy and paste the below xml contents in newly created XML file-

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE log4j:configuration SYSTEM “log4j.dtd”>
<log4j:configuration xmlns:log4j=”http://jakarta.apache.org/log4j/&#8221; debug=”false”>
<appender name=”fileAppender” class=”org.apache.log4j.FileAppender”>
<param name=”Threshold” value=”INFO” />
<param name=”File” value=”logfile.log“/>
<param name=”append” value=”true”/>
<layout class=”org.apache.log4j.PatternLayout”>
<param name=”ConversionPattern” value=”%d %-5p [%c{1}] %m %n” />
</layout>
</appender>
<root>
<level value=”INFO”/>
<appender-ref ref=”fileAppender”/>
</root>
</log4j:configuration>

  • Create new class file without main method and paste below code-

public class TestCase_Logging {
public static WebDriver driver=null;
private static Logger Log = Logger.getLogger(TestCase_POF.class.getName());
public static void main(String[] args) {
DOMConfigurator.configure(“log4j.xml”);
System.setProperty(“webdriver.ie.driver”, “D:/IE_Driver/IEDriverServer.exe”);
driver = new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Log.info(“Start the application.”);
driver.get(“https://google.com&#8221;);

}
}

Note: Highlighted codes are important to generate the log, so don’t miss them.

  • Now run the program and go to Project root folder. System has been generated logfile.log file.

Apache ANT Setup

Follow the below steps to set-up ANT build tool-

  1. Go to the folder which have been downloaded in this cases

“C:\Selenium\ANT\apache-ant-1.8.4-bin\apache-ant-1.8.4”

  1. Go to Computer properties->Click on Advance tab->Environment Variables
  2. In the System Variable Create an new variable name as “ANT_HOME”
  3. Paste the above ANT directory in the path text box Click Search for a PATH variable select the variable and click on Edit button
  4. Append a semicolon”;” and paste the above ANT directory appending “/bin”
  5. To check whether ANT is completely set into the Environment Go to Command prompt and type ant and hit enter key.
  6. After pressing ant you will see “Buildfile: build.xml does not exist! Build failed”
  7. This message will confirm you that Ant is configured properly.

How to reuse browser window among TestMethods in CodedUI?

Below code helps to reuse opened browser:-

BrowserWindow driver;

[TestMethod]
public void CaptureScreenshot()
{

driver = BrowserWindow.Launch(new System.Uri(“https://www.facebook.com&#8221;));
driver.TechnologyName = “Web”;
driver.CloseOnPlaybackCleanup = false;
driver.Maximized = true;

}

[TestMethod]
public void secondtest()
{
driver = new BrowserWindow();
driver.SearchProperties.Add(“Title”, “Welcome to Facebook – Log In, Sign Up or Learn More”);

HtmlEdit usr = new HtmlEdit(driver);
usr.SearchProperties.Add(“Id”, “email”);
usr.SetProperty(“Text”, “technicalt”);
}

How to take screenshots in CodedUI?

Below code will help to take entire screen screenshot-

Image MyScreenshot;
BrowserWindow driver;

[TestMethod]
public void CaptureScreenshot()
{

driver = BrowserWindow.Launch(new System.Uri(“https://www.facebook.com&#8221;));
driver.TechnologyName = “Web”;
driver.CloseOnPlaybackCleanup = false;
driver.Maximized = true;
MyScreenshot = driver.CaptureImage();
MyScreenshot.Save(@”D:\Windowscreenshot.png”, System.Drawing.Imaging.ImageFormat.Png);

}

If we need to take screenshot of any particular UI object then we can use below code-

Image MyScreenshot;
BrowserWindow driver;

[TestMethod]
public void CaptureScreenshot()
{

driver = BrowserWindow.Launch(new System.Uri(“https://www.facebook.com&#8221;));
driver.TechnologyName = “Web”;
driver.CloseOnPlaybackCleanup = false;
driver.Maximized = true;
MyScreenshot = driver.CaptureImage();
MyScreenshot.Save(@”D:\Windowscreenshot.png”, System.Drawing.Imaging.ImageFormat.Png);

HtmlLabel Login = new HtmlLabel(driver);
Login.SearchProperties.Add(“id”, “loginbutton”);

MyScreenshot = Login.CaptureImage();
MyScreenshot.Save(@”D:\Buttoncreenshot.png”, System.Drawing.Imaging.ImageFormat.Png);

}