Tuesday, October 4, 2016

BrowserMob Proxy Selenium network performance extension

It's been a while since I published some Java code here, but as Dexter Morgan would say: today is the day. If you want me to post Java tests more often please let me know in the comments.

BrowserMob Proxy is very useful tool which 'can capture performance data for web apps (via the HAR format), as well as manipulate browser behavior and traffic, such as whitelisting and blacklisting content, simulating network traffic and latency, and rewriting HTTP requests and responses'. It also has built-in support for Selenium integration which adds few nice features for our test suites with very little effort required.

You may of course say that Selenium is not performance testing tool (and rightly so), but nevertheless it can contribute to your testing in the following ways:
  • You can quickly assert that none of web requests returned undesired HTTP responses (like 404, 5xx). 
  • Captured *.har network traffic can be easily converted to Apache JMeter using various tools, for example Har2jmeter
  • *.har files can be used for comparison measures. If you do things right (i.e. your testing environment is exactly the same on each test run) changes in overall test execution time can indicate performance problem. Knowing that already you can just compare two *.har files (fast one and slow one) and check exactly which requests had slowed down. 
  • Modify user agent in requests
Those are just few things that comes to my mind right now, full list of BrowserMob Proxy features is listed here.

In order to start using BrowserMob Proxy add this Maven dependency to your project:

Now BrowserMob Proxy can be run using simple methods. I'm using TestNG annotation to start it before the tests, and close just after all of them finish. As you can see I capture all HTTP traffic headers here.

And this Gist shows how to add proxy settings to ChromeDriver. See my Browser capabilities explained post for more thorough description of browser configuration.

Now the most important thing - actual tests. As you can see I'm starting new Har capture on BrowserMob Proxy server before each test (it's called 'Awesome Testing Only Test' or 'Google Awesome Testing Test'). After last test step ends network traffic is saved to *.har file. I'm using FluentLenium syntax. Page Objects code can be found on my github project. Hopefully you have no problem understanding what the tests do :)

Our quest for obtaining *.har network traffic file is completed. Screenshot below shows how does it look like in Google HTTP Archive Viewer extension. It took 239 requests and 9.59 seconds to  successfully Google my blog.

File can also be accessed using external libraries. In code below I convert it JSON format using HarReader. It's not exactly part of the test so I put it in external class.

Remember: Complete Java code of this post (and every other) can be found on my Github project.