Why do we need Session Handling?

During test execution, the Selenium WebDriver has to interact with the browser all the time to execute given commands. At the time of execution, it is also possible that, before current execution completes, someone else starts execution of another script, in the same machine and in the same type of browser.

In such situation, we need a mechanism by which our two different executions should not overlap with each other. This can be achieved using Session Handling in Selenium.

How to achieve Session Handling in Selenium WebDriver?

If you check the source code of Selenium WebDriver, you will find a variable named as ‘sessionId’. Whenever we create a new instance of a WebDriver object, a new ‘sessionId’ will be generated and attached with that particular Firefox/Chrome/IE Driver ().

So anything we do after this will execute only in that particular Firefox browser session.

As this is an in-built functionality, there is no explicit need to assign the session id Code Example: Here two different sessions will be generated for two different WebDriver.

How to run Parallel Tests with Selenium

There are situations where you want to run multiple tests at the same time. In such cases, one can use “parallel” attribute

The parallel attribute of suite tag can accept four values: The attribute thread-count allows you to specify how many threads should be allocated for this execution. Complete Example: In this Example, three test cases will run parallel and fill login data in http://demo.guru99.com/ The Complete project will look like:

TestGuru99MultipleSession.java TestNG.XML

Test Case order and Dependency

You can set order and dependency of Test Case execution. Suppose you have two test cases , ‘testGuru99TC1’ and ‘testGuru99TC2’ and you want to execute test case ‘testGuru99TC2’ before ‘testGuru99TC1’. In that case we will use ‘dependsOnMethods’ attribute to make dependency and order of execution.

Summary

A new sessionID is created for a new instance of WebDriver. One session will bind with one particular browser. Using attribute thread and parallel, you run your scripts in parallel. You can use attribute dependency to set the order to test execution