Monday, October 6, 2014

A method to Data Drive your Selenium automated tests

I was just approached by a colleague who wanted to know how I data drive my tests when automating. Since this is probably a common enough question I figured I share in my blog.

One of my favorite approaches to data drive my tests is to use database tables to store the data. By using a database, such as MySql, you save yourself a lot of time in the maintenance and mining of the test data. You also get to, based on the query, select only certain type of data to be included during the current test run.

Lets say for example that you want to test the login function of your web application / site. You already have a user table set up in your database that has a large amount of user names, passwords in different combinations (e.g. valid user, invalid user, male, female, etc). You can leverage MySql by constructing a query that covers the specific users you would like run the test for.

Below is a quick example to try to illustrate the above.

DB test_data_tbl:
user_id        password        gender        active
user1          user1pw           male            1
user2          user2pw           male            0
user3          user3pw           female         1

Pseudo code:
1) Query the database for all valid users that are male
2) For each of the users returned
2a) Instantiate Selenium
2b) Open the home / start page
2c) Login to the application
2d) Close the session

Sample code in Perl:
1:  my $query = "SELECT user_id, password  
2:             FROM test_data_tbl  
3:             WHERE account_active = true  
4:             AND gender = 'male'  
5:             LIMIT 3;";  
7:  while ( my( $user_id, $password ) = $sth->fetchrow_array() ) {  
8:    # SsApp is a custom module where the stuff to set up selenium has been abstracted.  
9:    my $driver = Custom::SsApp::setup_selenium( \%desired_capabilities );  
10:    $driver->get( APPHOME );  
11:    $driver->find_element( $user_name_target, $user_name_locator )->send_keys( $user_id );  
12:    $driver->find_element( $password_target, $password_locator )->send_keys( $password );  
13:    $driver->quit();  
14:  }  

With this approach you can have easy access to your test data by just querying a database table. You can also replace the while loop with a foreach loop or whatever looping construct your programming language supports. The basic idea is to iterate through your data and execute each test using each data set.

No comments:

Post a Comment

Creative Commons License
VGP-Miami Web and Mobile Automation Blog by Alfred Vega is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.