QuickTest Professional 10.00


for QTP Scripts and Documents




I) Basic features of QTP
o QTP Launched in 2002 (Nov). By Mercury Interactive. Later taken over by HP, in 2007. o o o o QTP is an Object Based Testing Tool. QTP is for functional and Regression Testing. It follows Keyword driven approach. It supports Windows Operating Environment only.

o It supports GUI based (Graphical user interface) and Web based Applications Automation, does not support CUI (Command user interface) Applications. o It has multilingual support. (It supports English, Chinese, Japanese, Korean, etc languages with respect to license.) o It has adapted Microsoft Visual Basic Scripting edition for programming and excel like spread sheet for Data driven testing. o SQL (Structured query language) embedded or inserted with QTP, so we can use SQL statements directly from QTP. o It can be integrated with other Tools like WinRunner and Quality Center.

o It can be used for user interface (UI) test case automation and some limited (Non UI) Test case automation like File system operations and Data base operations. o It was derived from Astra QuickTest (mother tool of QTP).

o It supports IE (Internet Explorer) only for recording tests, for execution it supports other browsers like Mozilla and AOL, opera Etc apart from IE. o o QTP is a Desktop Application (I-Tier/Stand alone). QTP has two types of License, 1. Seat or Node locked License, 2. Concurrent or float license. Seat license for one system and Concurrent License, we can use for any system but one user at any time. If we want multiple concurrent licenses we can purchase. o QTP has UNI code support.




Version History of QTP
• • • • • • • • • • Astra Quick test (Mother tool of QTP) 1.0 to 5.0 Quick Test Professional 5.6 – Nov 2002 6.5 – 2003 8.0 – 2004 8.2, 8.3 –2005 9.0,9.1-2006 9.2- 2007 mercury interactive 9.5 –2008 H.P 10.00 –2009 January

Add-In Manager
QTP supports almost all industry leading technologies, but by default it does not support, with respect to add in license it supports. Default Add- ins of QTP are: • • • Activex Visual basic Web.

Other available Add Ins are: .NET, Java, People soft, Siebel, TE (Terminal Emulators), SAP for GUI, Sap for Web, Oracle Apps, Web Services etc. During QTP launching it shows Add in manger dialog box, Add in Manger lists out all available Add Ins in the company. User needs to select appropriate Add Ins for his application or AUT. One can select more than one Add Ins also; if we select unnecessary Add Ins QTP performance will be reduced.



com 4 .com Launching QTP We can launch QTP BY selecting desktop icon otherwise start > programs> QTP Professional > QTP. During launching it shows Add-In Manager.gcreddy@gcreddy. Quick Test Launches www. Add-in manager window Select appropriate Add Ins and click okay.gcreddy.

gcreddy@gcreddy.com II) Key Elements of QTP Tool Window www.com 5 .gcreddy.

com 6 .gcreddy@gcreddy. used for creating. (It is a local concept) www.com QTP Tool Window 1) Test Pane: It is programming interface of QTP. Test: It is a set of statements or set of one or more actions. (It is a local concept) Action: It is a set of Statements.gcreddy. editing. viewing and deleting test scripts.

gcreddy@gcreddy. method. www. Statements may have keywords.Test in VB script format.gcreddy. Test pane has 2 views. Expert view. It is a global concept.Test in Icon based GUI format. QTP Test Pane-Expert View Key word view. (Keyword such as function.com Statement: A minimal executable unit.com 7 . statement etc).

com 8 .gcreddy. 2) Active Screen It has an optional element of QTP. it takes snap shots of every statement that user performed action or operation on AUT. Navigation: Tools Menu> view options> we can use font size and colors etc. Note 3: User can customize Test pane view options.com QTP Test Pane-Keyword View Note1: Here in test pane Test is same but views are different.gcreddy@gcreddy. if you perform any modifications in one view those automatically reflects in another view. www. Note 2: Technical users use expert view and business user use key word view.

Note 1: Generally novice testers use this feature but it occupies lot of memory space on QTP.gcreddy@gcreddy.gcreddy. Navigation: View menu>active screen (for launching and closing) Configuring active screen: view>options>active screen tab>increase /Decrease capture level.com 9 .com It can be used for understanding and editing the test easily. Active Screen www. apply and okay.

Run time data table.for entire test /used for all actions in the test. excel sheets. Sql Server. 1. Enter test data directly into Data Table and use.gcreddy@gcreddy. (Attached with every test) 2. 2. Navigation: View menu>Data table (for launching and closing) Data driven Testing: Testing the same task(S) or same operation with multiple sets of test data. Data table available in 2 ways: 1. It can be used in two ways.com 3) Data Table It has an integrated spread sheet (Excel like).com 10 .for specific action only. (Available in result window) Run time is a carbon copy of design time data table.) It has two types of sheets. Importing data from external files (Flat files. oracle. Action Sheets. Global Sheet. etc.gcreddy. QTP has Data table methods for performing operations on data table. used for Data driven testing. Design time data table. www. 1. etc) and Data bases (MS access. 2.

(debug commands) www. We use step into.Data Table 4) Debug Viewer It is used for locating and rectifying or fixing errors.gcreddy@gcreddy. step over and step out commands for debugging.com QTP Tool window.gcreddy. It can be used for debugging the tests by step-by-step execution.com 11 .

gcreddy. www. library files etc).gcreddy@gcreddy. Navigation: View menu>debug viewer (for launching and closing) QTP Tool Window-Debug Viewer 5) Missing Resources It can be used for showing missing resources those attached to current test such as (recovery scenarios.com Through Debug viewer user can watch variables and change values of variables temporarily.com 12 .

www. Navigation: view menu> information QTP Tool Window-Information Pane 7) QTP Commands QTP Commands are available in 3 ways.gcreddy@gcreddy.com 13 .gcreddy.com Navigation: View menu >missing resources (for launching and closing) 6) Information This pane shows syntax errors automatically during saving the test.

Menu options 2. save tests. Insert Menu: Through this menu user can inserting check points. Through insert menu user can insert VB Script conditional and loop statements and transaction points (Start and End). deleting and splitting actions. information.gcreddy. Data Table. active screen. Edit Menu: It provides editing options and renaming. Tool Bar options 3. synchronizing points. www. out put values.gcreddy@gcreddy. Short cut keys (for Some important operations only) File menu: Through file menu user can create.com 14 . missing resources etc.com 1. Debug viewer. open existing tests. In this menu step generator available. export tests in zip format. View menu: Through this menu we can launch and close. using this user can generate recordable and non-recordable scripts.

analog recording and Low level recording. www. Run options and Run setting options Through this menu we can start normal recording.gcreddy. through this we can get object’s information.gcreddy@gcreddy. running and also we run tests.com 15 . Through this menu we can insert/remove/break points. Automation Menu: This menu provides Record. Through this menu we can contact technical support people and we can send feedback. Through this menu we can check for updates and download or install directly. In this menu object spy option available. Resources Menu: This menu provides object repository and recovery scenarios options. modify and delete recovery scenarios. through this option we can create virtual objects. Window Menu: This menu provides QTP tool window style settings. Debug Menu: This menu provides debug commands for step by step execution. Through this menu we can stop recoding. Through this menu we can create. call existing actions and copy existing actions. Through this menu we can create /modify/delete objects information and we can associate repositories. Help Menu: This menu provides QTP help as well as VB Script help. Through this menu we can set tool options as well as test pane view options.(Properties and values) In this menu Virtual object option available. Tools Menu: This menu provides Tools settings option. view options and object identification configuration.com Through insert menu user can create new actions.

gcreddy@gcreddy.com 16 .gcreddy.com III) QTP Testing Process Planning o o o o o Analyzing the AUT Generating/Selecting Test cases for Automation Collecting Test Data Automation Framework Implementation QTP Tool Settings Configuration Generating Tests o o o Recording Keyword driven methodology Descriptive Programming Enhancing Tests o Inserting Checkpoints o o o o o o o o o o Inserting Output values Adding Comments Synchronization Parameterization Inserting Flow Control Statements Calling Functions/Actions Generating Steps though Step Generator Inserting Transaction Points Using Regular Expressions Using Environment Variables Debugging Tests o Debug Commands & Break Points o o o Step by step execution Watching Variables Changing values of variables Running Tests o o o Normal Execution Batch Execution AOM Scripting www.

gcreddy. Java. or . Then determine the functionality that we want to test. To do this.com o o Tests Running through framework Scheduled Execution Analyzing Results o o o o QTP Result window Defining our own Results Exporting Results Deleting Results Reporting Defects o o o Manual Defect Reporting Tool based Defect Reporting Working with Quality Center Analyzing the AUT Before we begin creating a test. First. Each action should emulate an activity that a customer might perform when using your application. follow. we need to analyze our application and determine our testing needs. modular actions helps make our tests easier to read. so that we can load the required QuickTest add-ins.gcreddy@gcreddy.NET. try to keep the amount of steps we plan to include in each action to a minimum. consider how we can divide these processes into smaller units. which will be represented by our test's actions.com 17 . As we plan. consider the various activities that customers perform in our application to accomplish specific tasks. such as Web. Creating small. www. determine the development environments in which our application controls were developed. and maintain. Which objects and operations are relevant for the set of business processes that need to be tested? Which operations require customized keywords to provide additional functionality? While we are thinking about the business processes we want to test.

Select Record Option (It shows two Options : 1. 7. 6. The Track file is not editable. Record and Run only on If we select first option it records on any opened application on Desktop. it asks for the path of the AUT. but unable to record continuous mouse operations like Digital Signatures. Navigation: 1.com Recording and Running: In QTP there are 3 recording modes available for preparing Tests.gcreddy.com 18 . Simultaneously it stores objects information into object repository. It shows Record and Run Settings. 8.gcreddy@gcreddy. Analog Recording: It records the exact mouse and keyboard operations. Keep tool under recording mode www. We can use this mode for recording continuous mouse operations. Record and Run Test on any open window based applications 2. Normal Recording It records User Mouse and Keyboard operations on AUT with respect to objects. During recording QTP generates VbScript statements in Test Pane. Select type of Environment (Windows or Web) 4. Save the Test 2. If we select Second option. 1.) 5. Navigation: Automation>Record Or Select Record option on automation toolbar Or Use short cut key (F3) Steps for preparing a Test (through Recording): 1. paints etc. Click OK Perform actions on AUT Stop recording. Put AUT in base state 2. generates total user actions in a Track File. Select Record Option 3. It is not useful for recording normal operations why because it does not generate steps for each operation. After Providing the path it records only on that particular application. graphs.

Record relative to the screen 2. 2. 3.com 19 . Low Level Recording It records some operations on Non-supported environments apart from Normal operations. If we select Second option. after showing the Window it records with respect to that window co-ordinates. we have to show the window (AUT). Record relative to the following window If we select first option QTP records User operations with respect to Desktop coordinates. 1.com 2. Use Low Level Recording for recording in an environment not recognized by QTP.) 5. Launch AUT (or we can launch AUT through QTP) Select Record option Automation>Analog Recording Analog Recording Settings Dialog box opens (In this Dialog box two options available. Select any one option in the dialog box and click Start Analog record. 4. Navigation: 1.gcreddy. Automation >Low Level Recording Steps for preparing a TEST (through Low Level Recording): 1) Launch AUT (or we can launch AUT through QTP) 2) Select Record option 3) Automation> Low Level Recording 4) Perform options on AUT 5) Stop Recording 6) Save the Test www. 6. This mode records at the object level and records all run time objects as window or winobject Test objects.gcreddy@gcreddy. Automation >Analog Recording OR Use Short cut Key (Shift + ALT+F3) Steps for preparing a TEST (through Analog Recording): 1. It records User actions 7. Keep tool under recording mode 2. Stop Recording 3.

Run time objects Test objects Utility objects Automation objects/User defined objects.. WebPages. Software objects: We call windows. SystemUtil for launching/closing the application. Ex: WinEdit. etc… Test Objects: References of Run time objects. Ex: 1. 2. 4.com 20 . Types of Object in QTP: There are four types of object available in QTP. WinButton. edit boxes.gcreddy@gcreddy.gcreddy. WebButton. which has structure and properties. Ex: Run time objects Test objects in Test objects in VB windows Environment Environment buttons WinButton VBButton Edit box WinEdit VBEdit Check box Wincheckbox Vbcheckbox Test objects in web Environment WebButton WebEdit Webcheckbox Utility objects They are QTP reserved objects used for testing and result reporting.com Object Repository Object Repository: It is a storage place of QTP where we can store the objects information and it also acts as interface between the test script and the AUT in order to identify the objects during execution. as software objects. www. Run time objects: The objects present in the AUT. 1. 3. Object: Object is something. Ex: Buttons. check boxes etc. buttons. Link. links. etc… Note: Test objects names vary from one environment to another.

TSR extension) Local Repository: QTP creates a Local Repository for every action automatically during Recording. As it is QTP internal file user no need to save modifications. Local repository (. 1. those can be used for performing specific operations. User can add some more objects to Local repository User can perform rename.gcreddy@gcreddy. Ex: Creating objects in file system object class. Shared repository(. Navigation: Resource menu>object repository (Short cut key Ctrl+R) www. excel. Environment for using environment variables Automation objects/User defined objects User can create objects. Services for inserting transaction points 4.com 21 .gcreddy.connection class. There are two types of repository available in QTP. Application class etc. delete operations in local repository.com 2. adodb. 3. That cannot be shared among tests. Reporter for defining results. dictionary object class.MTR extension) 2.

Local Repository: Navigation: open local repository (resource menu>object repository) >objects>Add objects to Local>show the object>click ok (No need to save separately. That can be shared among number of tests. Shared Repository: Navigation: Resource menu>object repository manager>object>Add objects>show the window/object>click ok www.com 22 .Local Repository Shared Repository: User (Test Engineer) creates shared repository by adding objects. Using this method user can perform modifications on objects easily. it saves automatically) B.gcreddy.gcreddy@gcreddy.com QTP. Operations on Object Repository Adding objects a.

>close repository b. Note: After merging also. Deleting objects a. if we select third option it stores All objects including static objects.gcreddy@gcreddy.gcreddy. Shared Repository: Resources >object repository manager>file>open>browse path of the repository file >file>enable editing>select object &Right click>choose rename option>modify the name > release mouse>save the file & close repository manager. www. we have to select object classes then it stores that class objects. if we select second option it stores all default objects.com o o o o Selected object only Default object types All objects types Selected object types (If we select first option it stores Selected objects only. Local Repository: Resources > object repository >select object and right click >choose delete option >confirm deletion>. if we do not want source files we can delete. Associating objects repositories to an action Resources>Associate repositories>click add icon (+)>browse path of the repository>Associate with an action>click ok Merging Repositories Resources > object repository manager>tools>object repository merge tool >browse path of the first repository> browse path of the second repository>click ok>click close>save the merged repository>close the repository manager. source repository files will be available. >close repository b.) Renaming objects a. if we select fourth option.com 23 . we can select more than one class also. Local Repository: Resources > object repository >select object and right click >choose rename option >modify the name>release the mouse. Shared Repository: Resources >object repository manager>file>open>browse path of the repository file >file>enable editing>select object &Right click>choose delete option>confirm the deletion >save the file & close repository manager.

In local repository 3. Navigation: Select object in the repository >view>highlight in application>it highlights specified objects in the application. Importing Repository from XML file We can import XML file to our repository. Exporting Repository to an XML file We can export our repository file to an xml file.gcreddy. In Repository manager) View Options Locate in Repository This feature can be used for identifying objects from application to repository. Navigation: View>Locate in repository >show the object>click Ok>it locates specified object in the repository. Spying objects For getting objects information.gcreddy@gcreddy. using this we can get objects information. Navigation: File >export Test objects to XML Enter the file name and Save with xml extension. In tools Menu 2. Navigation>Tools>object spy>take hand icon & Show the object>get information (Object Spy shows the specific objects all available properties with their values) Note: As Object spy is an important feature.com Defining new test objects Navigation: Object>Define new test object >Select Environment>Select Class of the object>Enter name of the object>Click Add>click close>Select object >select property name>enter value (like this select one by one properties and enter values)>save Note: This feature can be used for preparing tests before the AUT is ready. Note: The purpose of this feature is Editing objects information outside of the QTP www. property & Values) QTP is providing a feature called Object Spy. Navigation: File>import from XML >browse path of the XML file >it loads objects. Highlight in Application This feature can be used for identifying objects from repository to application. it can be available in 3 Areas.(1. (Test objects names.com 24 .

we no need to have Object Repositories. Activate. OK . Advantages: a) Descriptive Programming based Test scripts are faster in execution than Repository based Test scripts. Dialog. Set.Property values or Logical Names of the Object 4.gcreddy. In this method of script creation. Descriptive programming is basically 2 types.Winedit("attached text:=Agent Name:"). then we can provide more properties information by separating with commas. b) Scripts are portable (we can run these scripts from any machine easily) c) Maintenance is easy (less amount of resources) d) We can start Test Execution process even though Application is not ready.Property names 3. WinEdit and WinButton – Test Objects 2. Agent Name:.exe" dialog("text:=Login").com 25 . 1.gcreddy@gcreddy.Set "mercury" dialog("text:=Login").Activate dialog("text:=Login"). we provide objects information directly into the script. Static Programming 2. Login. Password:. Setsecure.Methods Note2: If we feel one property information is not sufficient for recognizing the object uniquely.Winbutton("text:=OK".Click Note: 1. attached text . Dynamic Programming Static Programming In this style of script generation."width:=60"). Ex: Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a. www.com Descriptive Programming Entering / Providing objects information directly into the test script is called Descriptive Programming. Click .Set "asdf" dialog("text:=Login"). text.Winedit("attached text:=Password:").

This feature is available in Tools Menu.Set "mercury" Dialog(Login).Activate Dialog(Login). we can use object spy feature. Creating a Library file Place Constants in Notepad and save as .).exe" Dialog(Login).Winbutton(Ok). in local repository and in repository manager. properties and values).vbs file Associate the Library file to QTP (File->Settings->Resources-> Click add (+) icon-> Browse path of the Library file->Click Apply and click Ok buttons Otherwise.Winedit(Pwd").vbs)” After that create the Test Script using Constants Creating the Test Script using Constants: Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.com Note 3: If we want to get objects information (Test objects.gcreddy. then we can handle modifications easily. Agent="attached text:=Agent Name:" Const Pwd ="attached text:=Password:". if we take other line then we have to use Const Statement again.Winedit(Agent). ------------------------------------------------------------------If we want maintain ‘Objects information’ in centralized location then we can use Constants.Set "asdf" Dialog(Login).com 26 . Steps: Creating Constants: Const Login="text:=Login". we can load the library file during run-time Syntax: ExecuteFile “Path of the Library file(. Ok="text:=OK" Note: we can declare no of Constants in a line by separating with Camas (.Click Advantages: If we maintain Object Information in the centralized location.gcreddy@gcreddy. ------------------------------------------------------------------- www.

provide properties information and use description objects in the test script.value="OK" Generating Tests using Properties collection Objects Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.com 27 .gcreddy@gcreddy.Click Note1: Create Description objects and put into one library file.value=204 oAgent("attached text").Create oOk=description. Creating Properties Collection Objects Set Set Set Set oLogin=description.Set "asdf" Dialog(oLogin).com Dynamic Programming In this style of script generation.Create Entering Properties Information into Objects oLogin("text"). ---------------------------------------------------- www.value="Password:" oOk("text"). ---------------------------------------------------In this style of script creation also.Winedit(oAgent). by associating that library file. we can maintain Objects information in the Centralized location by putting collection objects in a Library file.value=320 oLogin("height"). Note2: Dynamic programming is some difficult in preparation than static programming but maintenance is very easy.Set "mercury" Dialog(oLogin).Create oPassword=description.Activate Dialog(oLogin).value="Login" oLogin("width").Winedit(oPassword).exe" Dialog(oLogin).value="Agent Name:" oPassword("attached text"). we can generate tests.Create oAgent=description.gcreddy. first we create description objects.Winbutton(oOK).

Close Browser(“Browser”). a. SET “Value” Ex: Dialog (“Login”). Browser window etc.Set c. Window("Flight Reservation"). Set Ex: Window("Flight Reservation").WinRadioButton("Business").Set “asdf” b.Close DBL CLICK: It Double clicks the object.select “item” Ex: A. Syntax: Object hierarchy.WinCheckBox("Order No.Winbutton(“ok”).Dialog box. Selecting a Radio Button Syntax: Object Hierarchy.gcreddy.WinEdit(“Agent Name”).gcreddy@gcreddy.Select "London" www. Click Ex: Dialog(“Login”).com Methods or Operations Activate: It activates dialog boxes/Windows Syntax: Object hierarchy.click Close Method: It closes the window.Set "ON" Select Method: It is used for selecting an item from a combo box or list box.WinComboBox("Fly From:"). Selecting/Deselecting check boxes Syntax:object Hierarchy. Dialog("Open Order").com 28 . Syntax: Object hierarchy. Close Ex: Window(“Flight Reservation”).Activate Click Method: It clicks on an object (Buttons) Syntax: Object hierarchy. Activate Ex: Dialog(“Login”). For setting the value of an edit box Syntax: Object Hierarchy. Set Method: It can be used in three ways.Activate Window(“Flight Reservation”).Set “ON/off” Ex: Window ("Flight Reservation").").

gcreddy.Navigate "http://www.WinComboBox("Fly From:").WinEdit("Tickets:").com 29 . any property value. Syntax: object hierarchy. It can be used for getting any object’s. Syntax: Variable = object hierarchy.GetContent Ex: x=Window("Flight Reservation").WinComboBox("Fly From:").google.getroproperty (“property name”) Ex: x=Window("Flight Reservation").gcreddy@gcreddy.getvisibletext Ex: x=Window("Flight Reservation"). Syntax: variable=object hierarchy.GetContent msgbox x Exist property: It checks whether the object is available or not.navigate “URL” Ex: Browser("Yahoo!").Dialog("Flights Table").getitemscount Ex: x=Window("Flight Reservation"). Syntax: Variable =object hierarchy. Window("Flight Reservation").Select "12572 GetVisibletext: It returns Text from the specified area.GetROProperty ("width") msgbox x Navigate Method: It opens a specified URL in the Browser.WinComboBox("Fly From:").co.in" Getitemscount: It returns number of items in a combobox.com B. Syntax: Object hierarchy.GetItemsCount msgbox x Getcontent: It returns all items from a combobox.WinList("From"). Syntax: Variable=object hierarchy.GetVisibleText msgbox x GetRoproperty: It returns current object property value.Exist(5) www.exist(time in seconds) Ex: Window("Flight Reservation").

Data base check point 6. XML Check point (from Application) 8. Inserting Transaction Points:(Start and End) Inserting Checkpoints Check point is a verification point. 1. it takes expected result from the user and compares with actual results during execution and provides test results.gcreddy. Adding Comments 4. There are several methods available in QTP for enhancing the TEST.com Enhancing Tests After generating the basic test. Parameterization 7. Image checkpoint 11. Text area check point 4. Table checkpoint Note 1: From 6 to 11 checkpoints are only for Web. Inserting Flow Control Statements 5. Accessibility check point 7. Inserting Check Points 2. www.gcreddy@gcreddy. Inserting Output Values 3.com 30 . XML Check point (from Resource) 9. Page check point 10. Synchronization 6. Text check point 3. we have to enhance the test in order to Test the AUT with respect to requirements. Bit map check point 5. Standard check point 2. Generating Steps through Step Generator 8. There are 11 Checkpoints available in QTP: 1.

com Note 2: From 9 to 11 checkpoints are hidden checkpoints. Through Active screen. Standard Checkpoint: It checks object property values.) www.gcreddy@gcreddy. we can insert these checkpoints through standard checkpoint. exact match. Through expert view.gcreddy. 2. Navigation: Keep tool under Recording mode >Insert menu > checkpoint > Text checkpoint > Show the object > click ok > Select options (Match case.com 31 . Inserting Standard check points through active screen: View > Active Screen >place cursor in desired location >Place mouse pointer on active screen & right click> choose insert standard checkpoint option > click ok > enter expected result > click ok Note: Inserting Standard check points through keyword view same as in expert view. We can use this checkpoint for checking any property value. 3. Note: We can insert standard checkpoints in 3 ways. Navigation for Inserting standard checkpoint Keep tool under recording mode > place cursor in desired location > Insert > check point > Standard checkpoint > Show the object > click okay > select property and enter expected results & click Ok and stop Recording. text not displayed. Through keyword view. 1. Navigation for Editing standard checkpoint Select Checkpoint statement and right click > choose checkpoint properties option > modify the value > click Ok. Navigation for Deleting standard checkpoint: Select Checkpoint statements and right click > choose delete option. 2) Text Checkpoint: It Checks object’s text property value in different ways. ignore spaces. 1.

4. 6.com 32 . Navigation: Keep tool under Recording mode > Insert menu> Checkpoint > Text area checkpoint > Mark the area of text > select one or more options (Match case. Note: here we do not need to put tool under Recording mode and we do not need AUT since data is from backend. we can compare complete bitmaps as well as part of the bitmaps. Bitmap checkpoint: It compares bitmaps. It is a configurable checkpoint. Database checkpoint: It checks Content of the back end Database.gcreddy. Accessibility check point: It checks whether the webpage in our web application is developed according to W3C (World Wide Web consortium) Rules and Regulations or not.com We can select one or more options > click ok & stop Recording. Configuring accessibility checkpoint: Tools menu> options >web > advanced > check/uncheck items > click apply > click ok Invigilation: www. exact match. ignore spaces.) Click ok and stop recording. 5. we can customize. Navigation: Insert > checkpoint > Database checkpoint >choose “specify SQL statement manually” option >click next > click create > select machine data source > Select DSN (QT_flight32) > click ok > enter SQL statement (select * from orders) > finish > click ok. text not displayed. 3) Text Area Checkpoint: It checks the text area present in the application. Navigation: Keep tool under Recording mode > Insert menu > Checkpoint > Bitmap checkpoint > show the Bitmap >click ok >select “check only selected area” option if we want to compare part of the bitmap > click ok >stop recording. according to our requirements.gcreddy@gcreddy.

Note: 1. according to W3C rules then Pass. Navigation: Keep tool under Recording mode in web environment > insert menu > checkpoint (from application)> show the xml pages >click ok > stop Recording. Image checkpoint: It checks Image property values. XML Check point (from Application) It checks content of the XML file. It is a hidden checkpoint.com Keep tool under recording mode with web environment >insert>checkpoint>accessibility checkpoint>show the webpage>click ok>click ok>stop recording. Navigation: Keep tool under Recording mode with web environment > Insert menu > checkpoint >standard checkpoint > show the image > select image > click ok > click ok >stop recording.com 33 . Page checkpoint: It checks number of Links. Note: 2. Result Criteria: a) If item is available but not according to W3C rules then fail. 8. 10. 9. b) If an item is available. Navigation: Keep tool under Recording mode with web environment > Insert menu > checkpoint > Standard checkpoint >show the web page > click ok > click ok > stop recording.gcreddy. c) If an item is not available then result would be pass 7. we can insert this through standard checkpoint. Navigation: Insert menu > checkpoint >xml checkpoint (from resource) > browse path of the XML File > click ok > click ok. and then we can go for inserting xml checkpoint from resource. If XML file is part of web application. separate path is not available then we can choose inserting XML checkpoints from application. If XML file is an individual and path available. Images and Loading time in a web page. XML Check point (from Resource) It checks content of the XML file.gcreddy@gcreddy. www.

Database output value 5. XML output value (From Application) 6. The values can later be used as input at a different point in the run session or we can use as input for another test.gcreddy.com 11. Navigation: Keep tool under Recording mode > Insert menu >output value> standard output value > show the object > click ok > select property > modify the column name (if required) > click ok >click ok >stop recording. it is located in QTP result window and can be retrieved later. Navigation: Keep tool under Recording mode under web environment > Insert menu > checkpoint > standard checkpoint >show the web table > click ok >stop recording. www. Standard output value 2. Inserting Output Values It is a step in which one or more values are captured during test execution. XML output value (From Resource) 1) Standard output value: We can use standard output values to output the properties values of most objects. Types of Output Values: 1.com 34 . Text area output value 4. Table checkpoint: It checks content of the web tables. It is stored in run time data table. Text output value 3.gcreddy@gcreddy.

com 35 . XML elements in XML www. Navigation: Insert menu> output value > Database output value> choose specify SQL statements manually >click next >click create >Select Machine Data source > Select Driver (QT_flight32) > click ok > enter SQL statement (select *from orders) > click finish > select data cells > click ok > Run and it will capture and see the results in run time table.> check in runtime table after running it.. Navigation: Keep tool under recording mode> Insert menu> output value > text output value > show the text >select one of the option(output text/text before/text after) > click modify if you want to change the column name > click ok > click ok. 4) Database output value: We can use Database output values to output the value of the contents of database cells. 3) Text Area output value: We can use text area output values to output text strings displayed within a defined area of the screen. 6) XML output Value (From Resource): We can use XML output values to output the values of documents. Navigation: Keep tool under recording mode with web environment > Insert menu > output value > XML output value from application > Show the XML document > select elements > click ok >stop recording.com 2) Text output value: We can use Text output values to output text strings displayed in an application.gcreddy@gcreddy. Navigation: Keep tool under recording mode > insert menu >output value > text area output value >Mark the text area >click modify the column name if necessary > click ok > again click ok > check in run time table after running it. 5) XML output value (from application): we can use XML output values to output the values of XML elements in XML documents. When creating a text output value we can output a part of the objects text and we can also specify text before and after options.gcreddy.

www. Use Apostrophe (‘) before the statement 2.com 36 . Use REM Command with single space before the statement Comment a Block of Statements: Navigation: Select block of statements > Edit menu> Advanced> Comment block Or After selecting block of statements use shortcut key Ctrl+M Uncomment a block of statements: Navigation: Select comment block>Edit menu> Advanced>Uncomment block Or After selecting comment block.com Navigation: Insert menu >output value> XML output value from resource > browse path of the XML file > click ok > select elements >click ok. Adding Comments Purpose of Comments: o o For making the script understandable For making the Script Disable from execution Syntax: 1. Use shortcut key ctrl+shift+M Inserting Flow Control Statements QTP adapted VB script engine for applying programming logic to tests.gcreddy@gcreddy.gcreddy. We can insert VB script conditional statements and loop statements for applying the logic. In VB script there are 2 types of conditional statements and four types of loop statements available.

com 37 . Syntax: object hierarchy.value. Sync Method (Only for WEB) 5. 1. Where Synchronization is required: During test execution QTP gives instructions one by one with same speed. it goes to next step immediately. that time we may not get proper execution and results. Inserting Synchronization point: Place cursor in desired location>keep tool under recording mode > Insert menu > Synchronization point > show the object > click ok > select property name & Value (True)>enter time in Mille seconds>click ok>Stop recording.com Synchronization It is a process of matching the speeds of both QTP and AUT in order to get proper execution and results. There are several methods available in QTP for synchronization.waitproperty “property name”.gcreddy@gcreddy. Inserting Synchronization points.time in milli seconds. 4. www. 2. Exist Property Inserting Wait Statements: We can insert wait statements in our test in order to make QTP to wait until AUT completes current operation. after completion of the current operations. Inserting Wait statements. Note: if we insert Synchronization points. Increasing Tool default synchronization time.gcreddy. In order to get proper results in between QTP & AUT synchronization is required. Syntax: Wait(time in seconds) Note: If we insert wait statements QTP waits up to maximum time even though operation is completed. 3. but AUT takes less time for some operations execution and more time for some operations execution. it does not wait up to maximum time.

Suppose in our test more statements are taking more time for execution then selecting “increasing tool time out” . www. but QTP does not wait up to maximum time unnecessarily. It is a performance concept but QTP supports measuring transaction time per user only. 2.StartTransaction "name of the transaction" ------statements ---------------services.Sync Selecting an appropriate Method: 1.gcreddy@gcreddy.Page("Yahoo! Toolbar").com 38 .com Increasing Tool default synchronization time: Navigation: File>settings>run tab>increase object synchronization time out>apply>ok Note: If we increase QTP tool default time that can be applied for all statements in the test. 3. even though some drawbacks are there in using wait statement.Sync Ex: Browser("Yahoo! Toolbar").gcreddy. Syntax: Object Hirearchy. Inserting Transaction Points We can insert Transaction points for measuring Transaction time. After completion of one statement execution it goes to next statement immediately. Suppose in our test one or more statements only are taking more time for execution then selecting “Inserting synchronization method” is better. Above two are local features but wait statement is Vbscript feature. Syntax: Services. it is better to use wait statement in functions.EndTransaction "name of the transaction" Note: We can insert multiple transactions points in a test. Sync Method: (only for WEB) Waits for the browser to complete current navigation.

Dynamic Test Data Submission: Through Loop Statements we can give strings also but every time user has to enter data.Click Window("Flight Reservation"). For orderno=1 to 10 step 1 ' for one increment step keyword is not mandatory Window("Flight Reservation").com 39 . Getting Test Data from front end objects."). Dynamic Test Data Submission 3. 1. Fetching Test Data directly from Databases (MS Acess. Types of Parameterization: We can parameterize tests in several ways.WinButton("OK"). oracle etc). 1. Through Data Table 4.com Parameterization Passing parameters.exe" www.WinCheckBox("Order No.Click Next 2.Dialog("Open Order").Dialog("Open Order"). Note: We can’t generate Strings.Set orderno Window("Flight Reservation").Set "ON" Window("Flight Reservation"). Through Loop Statements 2.gcreddy@gcreddy. For x=1 to 3 Agent =inputbox("enter an Agent Name") Password=inputbox("enter a password") invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.WinEdit("Edit").gcreddy.WinButton("Button").Dialog("Open Order"). through this concept we can pass multiple values. 6. Through Loop Statements: We can use loop statements for passing sequential numbers & Logical Numbers.Activate Window("Flight Reservation"). Fetching Test Data directly from External files (Flat files & Spreadsheets) 5. We use parameterization in Data Driven Testing. Data Driven Testing: Testing the Same operation with multiple sets of test data.

Activate Dialog("Login").gcreddy. Importing test data from external Flat files c.Close www.Set Agent Dialog("Login"). Agent = Datatable("Agent". Importing test data from Data bases. we can use Data Table for Data Driven Testing. Through Data Table: QTP adds one data table (Spreadsheet) for every test.WinEdit("Password:").WinEdit("Password:").WinButton("OK"). Steps: Generate the basic test>open data table(View>Data Table) Click on column header>enter the name of the field (like this we can create number of columns) > Enter Data>connect the data to test (variable=datatable(“column name”.Click Window("Flight Reservation"). Entering test data directly into data table and use b.Type micTab Dialog("Login").exe" Dialog("Login"). Importing test data from external Spread sheets d. Entering test data directly into data table and use.WinEdit("Agent Name:").WinEdit("Agent Name:").) Run the test.1) Pass parameters.Close Next 3.com 40 . Sheet id) Example: agent=datatable(“agent”.WinButton("OK").Activate Dialog("Login").SetSecure password Dialog("Login").1) pwd=Datatable ("Password".WinEdit("Agent Name:"). It has 3 types of usage a.com Dialog("Login").Type micTab Dialog("Login").Click Window("Flight Reservation").WinEdit("Agent Name:").gcreddy@gcreddy.SetSecure pwd Dialog("Login").1) invokeapplication "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a. A.Set Agent Dialog("Login").

1. Creating DSN & importing data Navigation: view>data table>Place mouse pointer on Data table>sheet>import>from database(Database query wizard opens)>choose ‘specify SQL statements manually>click next >click create>click new>select driver type>click next >browse path to store> enter DSN Name>Click Save>click next>click finish>select>browse the database& select>click ok>click ok>select DSN>click ok>enter SQL statement (select *from login)>click finish. Importing test data from external Spread sheets: Open Data Table (view>Data table)>place mouse pointer on data table and right click>file>import from file>Click ok>Browse path of the excel sheet (it imports data from the excel sheet) Connecting Test Data to QTP Test as above and run the test. Fetching Test Data directly from Excel Sheets 6) Fetching Test Data directly from Databases www. Start programs>MS Office>MS Access>file >new>Select blank Database>enter name of the database>Save with mdb extension. but first we have to create /get the DSN(Data source Name)& we have to use SQL Commands. Creating a Test Database: open MS Access (or we can use any other database).com 41 . c. 4.gcreddy@gcreddy. Importing test data from Data bases: Through Data table we can import Test Data from Data bases.com b.gcreddy. Importing test data from external files: Open Data Table (view>Data table)>place mouse pointer on data table and right click>file>import from file>Click ok>Browsw path of the file(it imports data from the flat file) Connecting Test Data to QTP Test as above and run the test. by using the DSN we can get data for number of tests. Entering Data into Tables: Select table>enter the data. Fetching Test Data directly from Flat files 5). Creating Tables: Select Create table in design view>Enter field name(Agent)and Select data type(text) Like this we can create number of fields>save&enter table name. D. Note: DSN Creation is one time activity.

Run ProductDir & app Dialog("Login").gcreddy. User defined variables: Variables that we predefine in the active external environment variables file. Built in variables: These are system defined variables. we can access from all tests but these are designed as read only.WinEdit("Password:"). Associating environment variable file: Navigation: File > settings >Environment > select variable type as user defined > check “load variables and values from the external file” > browse path of the xml file > click apply & ok. modifications are difficult.WinButton("OK").Click Creating user defined environment variables: Navigation: File > settings > Environment > select variable type as user defined > click add icon (+) > enter variable name & Value > click ok (like this we can create number of variables) > click export > browse path & enter file name.Set "gcreddy" Dialog("Login").WinEdit("Agent Name:").gcreddy@gcreddy. save with xml extension > click ok. We can create as many files as we want and we can change values of variables. 2. if we want to use some variables globally (From number of tests) declaring as global variables is better.com Environment Variables in QTP These are global variables. www.SetSecure "4b3c86f2107ff565cc195ba6c24739091b656407" Dialog("Login").Activate Dialog("Login"). Types of Environment variables: 1.exe" Systemutil. Usage of environment variables: Syntax: Variable = Environment(“environment variable name”) Ex: X=Environment (“ActionName”) Msgbox x Example Script: ProductDir =environment ("ProductDir") app= "\samples\flight\app\flight4a. If we declare as local variables in number of tests.com 42 .

loadfromfile”path of the xml file” Usage of user defined Environment variables: Associate environment file to current test: Variable = Environment (“Variable Name”) X=environment (“city”) Msgbox x Modifying Environment files: Select XML file>open with notepad>modify the values>Save.gcreddy@gcreddy.com Or We can load environment file directly Environment.com 43 .gcreddy. www.

Generate total test in the default action 2. insert. www. Splitting an action: Navigation: Place cursor in desired location>Edit menu>action>split action>Enter Action 1 name & action 2 name.delte) 2. Steps: 1.com Actions Action: A Set of Statements for performing a Task or Tasks.gcreddy@gcreddy. Purpose of Actions: For better understandability For reusing components Types of Actions: 1) Non Re usable actions 2) Re usable actions 3) External actions Operations on Actions: • Creating Actions • Splitting Actions • Renaming Actions • Deleting Actions • Calling an Action • Copying an Action • Making an Action Reusable/Non Reusable Creating an Action: Insert>call to new action>enter name of the action>click ok Steps: 1. Split into meaningful actions. Create required actions(ex login.com 44 .gcreddy. We divide our test into actions to streamline the process of testing. Prepare Scripts for those actions.

gcreddy.com Note: At a time we can split one actions into 2 actions. Making an action reusable: Select Non Reusable action >edit >action>action properties>check reusable action check box >click ok. Deleting Actions: Select desired action in action drop down box>edit menu>action>delete action>confirm deletion.gcreddy@gcreddy. www. Note: U can’t edit Copying an action: Insert>call to copy of action>browse path of the test>select desired action>click ok. Calling an action: Insert>call to existing action>browse path of the test>select desired action>click ok.com 45 . Renaming actions: Select desired action in action drop down box> edit menu>action>rename action>modify the name>click ok. Note: we can edit this action.

com VB Script (Fundamentals and Features) 1) Introduction 2) Comments 3) VB Script Variables 4) VB Script Data Types 5) VB Script Operators 6) Input/Output Operations 7) Constants 8) Conditional Statements 9) Loop through Code 10) VB Script Procedures 11) Procedures 12) VBScript syntax rules and guidelines 13) Errors www.gcreddy.gcreddy@gcreddy.com 46 .

0 Introduction • • • VBScript is a scripting language. and Millennium Editions and higher versions. 2000.vbs extension (instead of the default . type Msgbox "Hello VB Script" 3. 1. Start Notepad. Save this text file with a . In the case of a script embedded in an HTML page. or Visual InterDev. VbsEdit. When a VBScript is inserted into a HTML document. A Windows script is a text file. That is. For example. In the example. The VBScript can be executed immediately. Hello.3 Hosting Environments and Script Engines Scripts are often embedded in Web pages. Microsoft Visual C++. 5. Write your script. In the case of a script embedded in www. vbs. WSH plays the part of the host — it makes objects and services available for the script and provides a set of guidelines within which the script is executed. VBScript is a light version of Microsoft's programming language Visual Basic. Among other things. the Internet browser will read the HTML and interpret the VBScript. WSH creates an environment for hosting scripts. Microsoft Visual Basic Scripting Edition brings active scripting to a wide variety of environments. Navigate to the file you just saved. For example purposes.2 Creating a script with Notepad 1. when a script arrives at your computer. such as Internet Explorer. 1.gcreddy@gcreddy. including Web client scripting in Microsoft Internet Explorer and Web server scripting in Microsoft Internet Information Service. either in an HTML page (on the client side) or in an ASP page (on the server side). the engine component that interprets and runs the script code is loaded by the Web browser. and double-click it. or at a later event.com 47 . A scripting language is a lightweight programming language. 2.txt extension). We can also use your favorite HTML editor.vbs 4. Windows Script Host manages security and invokes the appropriate script engine Windows Script Host is built into Microsoft Windows 98. We can create a script with any text editor as long as we save our script with a WSH-compatible script extension (.1 Windows Script Host (WSH) It is a Windows administration tool. Windows Script Host invokes the VB Script engine and runs your script. a message box is displayed with the message "Hello VB Script" 1.wsf).js. or .com 1.gcreddy. The most commonly available text editor is already installed on our computer — Notepad.

Windows Script Host executes scripts that exist outside an HTML or ASP page and that stand on their own as text files. 1. We can use other script engines. we write scripts in either Microsoft JScript or VBScript. a stand-alone script written in VBScript has the .vbs extension. When we run one of these types of files. and Python.gcreddy@gcreddy. such as Perl. which invokes the associated script engine to interpret and run the file. the two script engines that ship with Microsoft Windows 98. the engine that interprets and runs the script code is built into Internet Information Services (IIS). www.com 48 . These extensions are registered with Windows.js extension. with Windows Script Host.gcreddy. A stand-alone script written in JScript has the . REXX. 2000 and Millennium Editions. Windows starts Windows Script Host.com an ASP page.4 Available Script Engines Generally.

2.0 Purpose of comments: o o We can use comments for making the script understandable.gcreddy@gcreddy. We can use comments for making one or more statements disable from execution.0 Comments The comment argument is the text of any comment we want to include.com 49 .2 Comment/Uncomment a block of statements o Select block of statement and use short cut key Ctrl + M (for comment) o Select comment block and use short cut key Ctrl + Shift + M (for uncomment) www. a space is required before comment.gcreddy. 2.) Or Apostrophe (') symbol before the comment 2.1 Syntax Rem comment (After the Rem keyword.com 2.

Top.com 50 .gcreddy. For that reason. For example: Dim city Dim x We declare multiple variables by separating each variable name with a comma. www. Left.gcreddy@gcreddy. Must not exceed 255 characters. Right We can also declare a variable implicitly by simply using its name in our script.com 3. That is not generally a good practice because we could misspell the variable name in one or more places. Bottom. Option Explicit ' Force explicit variable declaration. Cannot contain an embedded period. MyInt = 10 ' Undeclared variable generates error.3 Naming Restrictions for Variables Variable names follow the standard rules for naming anything in VBScript. 3. and the Private statement. the Public statement.0 VB Script Variables A variable is a convenient placeholder that refers to a computer memory location where we can store program information that may change during the time our script is running. A variable name: • • • • Must begin with an alphabetic character. MyVar = 10 ' Declared variable does not generate error. causing unexpected results when our script is run. 3. For example: Dim x. the Option Explicit statement is available to require explicit declaration of all variables.1 Declaring Variables We declare variables explicitly in our script using the Dim statement. Dim MyVar ' Declare variable. The Option Explicit statement should be the first statement in our script. 3.2 Option Explicit Forces explicit declaration of all variables in a script. Must be unique in the scope in which it is declared.

At procedure level. only code within that procedure can access or change the value of that variable If we declare a variable outside a procedure. except that the declaration of an array variable uses parentheses () following the variable name. When we declare a variable within a procedure. Array variables and scalar variables are declared in the same way. is called an array variable. all arrays in VBScript are zerobased. we make it recognizable to all the procedures in our script.4 Scope of Variables o o o A variable's scope is determined by where you declare it.7 Scalar Variables and Array Variables A variable containing a single value is a scalar variable. For example: B = 200 City = “Hyderabad” 3. The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running. so this array actually contains 4 elements. Example: Dim A(3) Although the number shown in the parentheses is 3. 3.gcreddy. and it has scriptlevel scope. A variable containing a series of values.5 Life Time of Variables o o o The lifetime of a variable depends on how long it exists.6 Assigning Values to Variables Values are assigned to variables creating an expression as follows: The variable is on the left side of the expression and the value you want to assign to the variable is on the right.com 51 . 3. Beginning at zero and ending at 10. We assign data to each of the elements of the array using an index into the array. This is a script-level variable. a variable exists only as long as you are in the procedure. data can be assigned to the elements of an array as follows: A(0) = 256 A(1) = 324 www.gcreddy@gcreddy.com 3.

the second number is the number of columns. although most people can't comprehend more than three or four dimensions.com 52 . the first number is always the number of rows. for a dynamic array. Arrays aren't limited to a single dimension. For example: SomeVariable = A(4) Arrays aren't limited to a single dimension. you must subsequently use ReDim to determine the number of dimensions and the size of each dimension. This is called a dynamic array. although most people can't comprehend more than three or four dimensions. You can have as many as 60 dimensions. www.gcreddy. In the following example. 3. but uses the Preserve keyword to preserve the contents of the array as the resizing takes place.com A(2) = 100 A(3) = 55 Similarly. In the following example. the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns: Dim MyTable(5. 10) In a two-dimensional array. the data can be retrieved from any element using an index into the particular array element you want.gcreddy@gcreddy.8 Dynamic Arrays We can also declare an array whose size changes during the time our script is running. The array is initially declared within a procedure using either the Dim statement or using the ReDim statement. A subsequent ReDim statement resizes the array to 30. However. ReDim sets the initial size of the dynamic array to 25. no size or number of dimensions is placed inside the parentheses. For example: Dim MyArray() ReDim AnotherArray() To use a dynamic array. We can have as many as 60 dimensions.

floating-point number in the range -3.685. Contains either True or False. Contains a number that represents a date between January 1. Variant intentionally contains no valid data. we can just put the kind of data we want in a Variant.0 VB Script Data Types VBScript has only one data type called a Variant.94065645841247E-324 to 1. Most of the time.337.203.94065645841247E-324 for negative values.gcreddy.477. depending on how it is used.477. 1.483.79769313486232E308 for positive values.648 to 2. Contains a variable-length string that can be up to approximately 2 billion characters in length. We can also have a rich variety of numeric information ranging in size from Boolean values to huge floating-point numbers.5808 to 922.5807. Because Variant is the only data type in VBScript. Contains a single-precision.gcreddy@gcreddy. For example. When used with other date or time data. we can have numeric information that represents a date or a time. although if we make an array smaller. the result is always expressed as a date or a time. we lose the data in the eliminated elements.401298E-45 for negative values. Contains integer in the range -32. Value is 0 for numeric variables or a zerolength string ("") for string variables. The following table shows subtypes of data that a Variant can contain.com 53 . 4.147. Contains integer in the range -2.com ReDim MyArray(25) ReDim Preserve MyArray(30) There is no limit to the number of times we can resize a dynamic array.147.768 to 32. These different categories of information that can be contained in a Variant are called subtypes.483.402823E38 for positive values.203. www. it is also the data type returned by all functions in VBScript. -922. Contains integer in the range 0 to 255.337.767. Subtype Empty Null Boolean Byte Integer Currency Long Single Double Date (Time) String Description Variant is uninitialized. 4.685.647. Contains a double-precision. 9999. A Variant is a special kind of data type that can contain different kinds of information.401298E-45 to 3. floating-point number in the range -1.402823E38 to -1.79769313486232E308 to -4. 4. 100 to December 31.1 Variant Subtypes Beyond the simple numeric or string classifications. and the Variant behaves in a way that is most appropriate for the data it contains. a Variant can make further distinctions about the specific nature of numeric information.

gcreddy@gcreddy. and logical operators. When expressions contain operators from more than one category. standard operator precedence is maintained. 4. Arithmetic and logical operators are evaluated in the following order of precedence.com 54 . comparison operators. arithmetic operators are evaluated first. Divides two numbers and returns only the remainder.1 Operator Precedence When several operations occur in an expression. We can use conversion functions to convert data from one subtype to another. the VarType function returns information about how your data is stored within a Variant.com Object Error Contains an object. In addition.0 VB Script Operators Operators are used for performing mathematical. Divides two numbers and returns a floating-point result. Divides two numbers and returns an integer result. and logical operators are evaluated last. including arithmetic operators. Operations within parentheses are always performed before those outside. they are evaluated in the left-to-right order in which they appear. We can use parentheses to override the order of precedence and force some parts of an expression to be evaluated before others. comparison operators are evaluated next. that is. concatenation operators. 4. Multiplies two numbers. comparison and logical operations. Within parentheses. Comparison operators all have equal precedence. Contains an error number.2 Arithmetic Operators: Operator 1) Exponentiation Operator (^) 2) Multiplication Operator (*) 3) Division Operator (/) 4) Integer Division Operator (\) 5) Mod Operator Description Raises a number to the power of an exponent. www. VBScript has a full range of operators. each part is evaluated and resolved in a predetermined order called operator precedence. 5. however.gcreddy.

gcreddy. Operator 1) = 2) <> 3) < 4) > Description Equal to Not equal to Less than Grater than Operator 5) <= 6) >= 7) Is Description Less than or equal to Greater than or equal to Object equivalence Sums two numbers.5 Logical Operators Operator 1) Not 2) And 3) Or 4) Xor 5) Eqv 6) Imp Description Performs logical negation on an expression. Forces string concatenation of two expressions. 2) Both expressions are strings Concatenate. Finds the difference between two numbers or indicates the negative value of a numeric expression.gcreddy@gcreddy.com 6) Addition Operator (+) 7) Subtraction Operator (-) 8) Concatenation Operator (&) 4. Performs a logical disjunction on two expressions. 4. If Then 1) Both expressions are numeric Add.com 55 . Performs a logical equivalence on two expressions. Performs a logical implication on two expressions.3 Comparison Operators Used to compare expressions. 3) One expression is numeric and Add. Syntax result= Not expression result= expression1 expression2 result= expression1 expression2 result= expression1 expression2 result= expression1 expression2 And Or Xor Eqv result= expression1 Imp expression2 www. 2) Concatenation Operator (&) 4. Performs a logical conjunction on two expressions.4 Concatenation Operators Operator 1) Addition Operator (+) Description Sums two numbers. Performs a logical exclusion on two expressions. the other is a string Forces string concatenation of two expressions.

1 Creating Constants We create user-defined constants in VBScript using the Const statement. 7.1 InputBox Function Displays a prompt in a dialog box. depending on which button is clicked. x= 27 www. Example: Const MyString = "This is my string. Const statement Declares constants for use in place of literal values. For example: Const price= 100.gcreddy@gcreddy. We declare multiple constants by separating each constant name and value with a comma.gcreddy.com 6) Input/Output Operations 6. 7) VB Script Constants A constant is a meaningful name that takes the place of a number or string and never changes. "MsgBox Example") ' MyVar contains either 1 or 2." Const MyAge = 49 Const CutoffDate = #6-1-97# Note that String literal is enclosed in quotation marks (" "). city= “Hyderabad”. Example: Dim Input Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) 6.2 MsgBox Function Displays a message in a dialog box. Using the Const statement. Example: Dim MyVar MyVar = MsgBox ("Hello World!". Represent Date literals and time literals by enclosing them in number signs (#). waits for the user to click a button. 65. and returns the contents of the text box. we can create string or numeric constants with meaningful names and assign them literal values. and returns a value indicating which button the user clicked. waits for the user to input text or click a button.com 56 .

depending on the result. Example: www.. to specify one or more statements to run.1 Making Decisions Using If..1 Running a Statements if a Condition is True (single statement) To run only one statement when a condition is True..... we must use the multiple-line (or block) syntax.1..Else statement. Usually the condition is an expression that uses a comparison operator to compare one value or variable with another.com 57 . This syntax includes the End If statement. use the single-line syntax for the If..Else statement to define two blocks of executable statements: one block to run if the condition is True.com 8) Conditional Statements We can control the flow of our script with conditional statements and looping statements.Else The If.... Dim x x= 20 If x>10 Then msgbox "Hello G.Then.Then. Dim myDate myDate = #2/13/98# If myDate < Now Then myDate = Now 8.. The following conditional statements are available in VBScript: 1) If…Then…Else Statement 2) Select Case Statement 8.. If.Then..gcreddy@gcreddy.Reddy" msgbox "x value is: "&x msgbox "Bye Bye" End If 8. Using conditional statements.1. 8.Else statements can be nested to as many levels as you need. the other block to run if the condition is False.3 Running Certain Statements if a Condition is True and Running Others if a Condition is False We can use an If.Then.Then. we can write VBScript code that makes decisions and repeats actions.gcreddy..2 Running Statements if a Condition is True (multiple statements) To run more than one line of code.....1.Else statement is used to evaluate whether a condition is True or False and..C.

Then.Else statement allows us to choose from several alternatives...) Example: Dim State.1.4 Deciding Between Several Alternatives A variation on the If.1..com Dim x x= Inputbox (" Enter a value") If x>100 Then Msgbox "Hello G..Reddy" Msgbox "X is a Small Number" Msgbox "X value is "&x Else IF x>100 and x<=500 Then Msgbox "Hello GCR" Msgbox "X is a Medium Number" Else IF x>500 and x<=1000 Then Msgbox "Hello Chandra Mohan Reddy" Msgbox "X is a Large Number" Else End If End If End If Msgbox "Hello Sir" Msgbox "X is a Grand Number" 8.C....5 Executing a certain block of statements when two / more conditions are True (Nested If..C.com 58 ..Reddy" Msgbox "X is a Big Number" Msgbox "X value is: "&X Else Msgbox "GCR" Msgbox "X is a Small Number" Msgbox "X value is: "&X End If 8.gcreddy@gcreddy.. Region State=Inputbox ("Enter a State") Region=Inputbox ("Enter a Region") www. Adding ElseIf clauses expands the functionality of the If.Else statement so we can control program flow based on different possibilities.gcreddy. Example: Dim x x= Inputbox (" Enter a value") If x>0 and x<=100 Then Msgbox "Hello G.Then.

y values is "&Result Result= x-y Msgbox "Hello G. but it makes code more efficient and readable..C.C.y values is "&Result Result= x/y Case "sub" Case "div" www..y.Else statement... A Select Case statement provides capability similar to the If.gcreddy.2 Making Decisions with Select Case The Select Case structure provides an alternative to If..y values is "&Result Case "mul" Result= x*y Msgbox "Hello G.. Result x= Inputbox (" Enter x value") y= Inputbox ("Enter y value") Operation= Inputbox ("Enter an Operation") Select Case Operation Case "add" Result= cdbl (x)+cdbl (y) Msgbox "Hello G.com 59 ..C. Example: Option explicit Dim x.Reddy" Msgbox "Addition of x.Reddy" Msgbox "Substraction of x.Then.C. Operation..ElseIf for selectively executing one block of statements from among multiple blocks of statements.Reddy" Msgbox "Multiplication of x.Then.com If state= "AP" Then If Region= "Telangana" Then msgbox "Hello G.gcreddy@gcreddy.Reddy" msgbox "Dist count is 10" Else if Region= "Rayalasema" Then msgbox "Hello GCR" msgbox "Dist count is 4" Else If Region= "Costal" Then msgbox "Hello Chandra mohan Reddy" msgbox "Dist count is 9" End End End End If If If If 8.

com Msgbox "Hello G.num2. sum num1=inputbox ("Enter num1") num2=inputbox ("Enter num2") sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require Case Else www.3.C.Reddy" Msgbox "Mod of x.3 Read two numbers and display the sum? Dim num1.1 Write a program for finding out whether the given year is a leap year or not? Dim xyear xyear=inputbox ("Enter Year") If xyear mod 4=0 Then msgbox "This is a Leap year" Else msgbox "This is NOT" End If 8.gcreddy.C.y values is "&Result Case "mod" Result= x mod y Msgbox "Hello G.y values is "&Result Msgbox "Hello G.C.Reddy" Msgbox"Exponentation of x.3 Other Examples 8.3. Even number or Odd number? Dim num num=inputbox ("Enter a number") If num mod 2=0 Then msgbox "This is a Even Number" Else msgbox "This is a Odd Number" End If 8.Reddy" msgbox "Wrong Operation" End Select 8.gcreddy@gcreddy.Reddy" Msgbox "Division of x.com 60 .C.y values is "&Result Case "expo" Result= x^y Msgbox "Hello G.3.2 Write a program for finding out whether the given number is.

r= rate of interest msgbox ("Simple Interest is " &si) 8. you entered is not a 4 digit number" End If 8.4 Read P. t=time in years.R values and Calculate the Simple Interest? Dim p. r.3.com 61 .gcreddy.6 Read any Four digit number and display the number in reverse order? Dim num. si p=inputbox ("Enter Principle") t=inputbox ("Enter Time") r=inputbox ("Enter Rate of Interest") si= (p*t*r)/100 ' p= principle amount.gcreddy@gcreddy.3) rev=rev*10 + num mod 10 num=num/10 num= left(num.3.1) rev=rev*10 + num mod 10 www.2) rev=rev*10 + num mod 10 num=num/10 num= left(num.com msgbox ("Sum is " &sum) 8. calculate & display the sum of the number or display Error message if the number is not a four digit number? Dim num.3.T. 1) sum=sum+num mod 10 msgbox ("Sum is " &sum) else msgbox "Number.5 Read Four digit number.t. sum num=inputbox ("Enter a Four digit number") If Len(num) = 4 Then sum=0 sum=sum+num mod 10 num=num/10 num= left (num.rev num= inputbox("Enter a number") If len(num)=4 Then rev=rev*10 + num mod 10 num=num/10 num= left(num. 2) sum=sum+num mod 10 num=num/10 num= left (num. 3) sum=sum+num mod 10 num=num/10 num= left (num.

tot e=inputbox ("Enter english Marks") m=inputbox ("Enter maths Marks") p=inputbox ("Enter physics Marks") c=inputbox ("Enter chemistry Marks") tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c) msgbox tot If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then msgbox "Grade is Distinction" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=240 and tot<300 Then msgbox "Grade is First" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=200 and tot<240 Then msgbox "Grade is Second" else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=160 and tot<200 Then msgbox "Grade is Third" else msgbox "No Grade.7 Read 4 subjects marks.com 62 . calculate the Total marks and grade? (a) If average marks Greater than or equal to 75. otherwise 'no grade fail') Dim e. then grade is Second d) If average marks Greater than or equal to 40 and less than 50 .3. then grade is Third e) Minimum marks 35 for any subject.m. grade is Distinction b) If average marks Greater than or equal to 60 and less than 75 .n n=Inputbox ("Enter a Vaule") www.8 Display Odd numbers up to n? Dim num.gcreddy@gcreddy.gcreddy.com msgbox "Reverse Order of the number is "&rev Else End If 8. you entered is not a 4 digit number" 8.c.3.p. then grade is First c) If average marks Greater than or equal to 50 and less than 60 . Fail" End End End End If If If If msgbox "Number.

gcreddy@gcreddy.11 Display Natural numbers in reverse order up to n? Dim num. n..13 Display Natural numbers sum up to n? (using While. 8. sum n= inputbox ("Enter a Value") sum=0 For num= 1 to n step 1 sum= sum+num Next msgbox sum 8.3.Until.opentextfile ("E:\gcr. n.com 63 .Wend Loop) Dim num. true) myfile.Next Loop) Dim num..Loop) www.txt"...3.writeline num myfile.n n=Inputbox ("Enter a Vaule") For num=n to 1 step -1 msgbox num Next 8.n n=Inputbox ("Enter a Vaule") For num= 2 to n step 2 msgbox num Next 8.com For num= 1 to n step 2 msgbox num Next 8.. fso. n.10 display natural numers up to n and write in a text file? Dim num.14 Display Natural numbers sum up to n? (using Do. myfile n= inputbox ("Enter any Value") num=1 For num= 1 to n step 1 Set fso= createobject ("scripting...9 Display Even numbers up to n? Dim num.close Next 8.gcreddy..filesystemobject") set myfile=fso.12 Display Natural numbers sum up to n? (using For. sum n= inputbox ("Enter a Value") While num <=cdbl (n) sum= sum+num num=num+1 Wend msgbox sum 8.

y. 8.x. 3.15 Write a Function for Natural Numbers sum up to n? Function NNumCou (n) Dim num.x. len d3=mid (num. 5. 7.16 Verify weather the entered 10 digit value is a numeric value or not? Dim a.num num=Inputbox ("Enter a Phone Number") d1= left (num.num num=Inputbox ("Enter a Phone Number") www. len d8=mid (num. 6. len d5=mid (num.com Dim num.com 64 .z.gcreddy. n.17 Verify weather the entered value is a 10 digit value or not and Numeric value or not? (using multiple if conditions) Dim a. len d9=mid (num. len d4=mid (num. len d6=mid (num. 4.y.gcreddy@gcreddy.1) d10=Right (num. sum n= inputbox ("Enter a Value") sum=0 num=1 Do sum= sum+num num=num+1 Loop Until num =cdbl (n+1) msgbox sum 8. len d7=mid (num. len (1)) (1)) (1)) (1)) (1)) (1)) (1)) (1)) If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" else Msgbox "It is NOT Numeric" End If 8.z.1) d2=mid (num. 2. 9. sum sum=0 For num= 1 to n step 1 sum= sum+num Next msgbox sum End Function 8.

len d5=mid (num.gcreddy.gcreddy@gcreddy. 2. len d3=mid (num. 5. 3. len d8=mid (num. len (1)) (1)) (1)) (1)) (1)) (1)) (1)) (1)) If len (num) =10 Then If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then msgbox "It is a Numeric Value" End If End If If len (num) <> 10 Then Msgbox "It is NOT valid Number " End If www.com d1= left (num.1) d10=Right (num. 4. 8. 7.com 65 .1) d2=mid (num. 6. len d9=mid (num. 9. len d7=mid (num. len d4=mid (num. len d6=mid (num.

.1 Using Do Loops We can use Do.Loop statements to run a block of statements an indefinite number of times.com 9) Looping Through Code o Looping allows us to run a group of statements repeatedly.Wend: Loops while a condition is True. The following looping statements are available in VBScript: • • • • Do. o Others repeat statements until a condition is True. o Some loops repeat statements until a condition is False.Reddy" Msgbox "Hello QTP" Loop b) Do Statements --------------------Loop While condition Example: www. For.C. While..Loop: Loops while or until a condition is True...Next: Uses a counter to run statements a specified number of times...Next: Repeats a group of statements for each item in a collection or each element of an array. 9. The statements are repeated either while a condition is True or until a condition becomes True.1. For Each... we can use this below syntax: Example: Dim x Do While x<5 x=x+1 Msgbox "Hello G..gcreddy. o There are also loops that repeat statements a specific number of times..gcreddy@gcreddy.1 Repeating Statements While a Condition is True Repeats a block of statements while a condition is True or until a condition becomes True a) Do While condition Statements --------------------Loop Or. 9.com 66 .

Wend Statement Executes a series of statements as long as a given condition is True. we can use this below syntax: Example: Dim x x=1 Do Msgbox “Hello G.gcreddy..com Dim x x=1 Do Msgbox "Hello G. we can use this below syntax: Example: Dim x Do Until x=5 x=x+1 Msgbox "G. Syntax: www.Reddy” Msgbox "Hello QTP" x=x+1 Loop Until x=5 9.2 Repeating a Statement Until a Condition Becomes True c) Do Until condition Statements --------------------Loop Or.Reddy" Msgbox "Hello QTP" Loop Or. we can use this below syntax: d) Do Statements --------------------Loop Until condition Or.2 While.C.C..C.Reddy" Msgbox "Hello QTP" x=x+1 Loop While x<5 9.1.gcreddy@gcreddy.com 67 .

gcreddy.gcreddy@gcreddy..Reddy" msgbox "Hello QTP" Wend 9.com While condition Statements --------------------Wend Example: Dim x x=0 While x<5 x=x+1 msgbox "Hello G.com 68 .3 For..Next Statement Repeats a group of statements a specified number of times.. Syntax: For counter = start to end [Step step] statements Next Example: Dim x For x= 1 to 5 step 1 Msgbox "Hello G.b.Reddy" Next 9.C.Next Statement Repeats a group of statements for each element in an array or collection.x (3) a=20 b=30 x(0)= "Addition is "& a+b www.4 For Each.C.. Syntax: For Each item In array Statements Next Example: Dim a.

there are two kinds of procedures.gcreddy@gcreddy.com x(1)="Substraction is " & a-b x(2)= "Multiplication is " & a*b x(3)= "Division is " & a/b For Each element In x msgbox element Next Example: MyArray = Array("one"."two"."five") For Each element In MyArray msgbox element Next 10) VB Script Procedures In VBScript."four".1 Sub Procedures A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value. Syntax: Sub Procedure name () Statements --------------------End Sub Or Sub Procedure name (argument1.com 69 ."three". If a Sub procedure has no arguments. its Sub statement must include an empty set of parentheses (). the Sub procedure and the Function procedure. or expressions that are passed by a calling procedure).gcreddy. A Sub procedure can take arguments (constants. argument2) Statements ----------- www. 11. variables.

----------End Sub Example: 1 Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C." End Sub Example: 2 11.2 Function Procedures A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant. Syntax: Function Procedure name () Statements --------------------End Function Or Function Procedure name (argument1, argument2) Statements



--------------------End Function Example: 1 Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function Example: 2 Function cal(a,b,c) cal = (a+b+c) End Function 11.3 Getting Data into and out of Procedures o o Each piece of data is passed into our procedures using an argument. Arguments serve as placeholders for the data we want to pass into our procedure. We can name our arguments any valid variable name. When we create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. Any arguments are placed inside these parentheses, separated by commas.


11.4 Using Sub and Function Procedures in Code A Function in our code must always be used on the right side of a variable assignment or in an expression. For example: Temp = Celsius(fDegrees) -OrMsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."

To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses.



The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing.

Call MyProc(firstarg, secondarg) MyProc firstarg, secondarg

Notice that the parentheses are omitted in the call when the Call statement isn't used.



Dim num num=157.56 num=Abs(num) msgbox num 'Output: 157.56 num=Abs(num) msgbox num 'Output: 157.56 num=-157.gcreddy.56 Note: It provide positive value www.gcreddy@gcreddy.com 11) VB Script Built in Functions 1) Asc Function 'Returns ANSI character code corresponding to first letter in a string Dim val val="hyderabad" val=Asc(val) msgbox val 2) Chr Function 'Returns the character associated with the specified ANSI character code. Dim val val=65 val=Chr(val) msgbox val 'Output: A 3) Date Function It returns current system Date Dim myDate myDate=Date msgbox myDate 4) Abs Function It returns obsolute value of the given number.com 73 .

"Chennai". "Nellore") msgbox var(0) 'output: Hyderabad msgbox var(1) 'output: Chennai msgbox var(2) 'output: Nellore 'List of numeric values var=Array(100.200.gcreddy@gcreddy. 300) msgbox var(0) 'output: 100 msgbox var(1) 'output: 200 msgbox var(2) 'output: 300 'List of mixed values var=Array(100.x 'List of strings var1=Array("Hyderabad". "Nellore") x=isArray(var1) 'It returns True/False like Result msgbox x x=isArray(var2) msgbox x www.com 5) Array Function We can enter list of values using this function Ex: Dim var 'List of strings var=Array("Hyderabad".com 74 . #01-05-2010#) msgbox var(0) 'output: 100 msgbox var(1) 'output: India msgbox var(2) 'output: 01/05/2010 6) IsArray Function It checks weather the given variable is an Array or not Dim var1. var2."Chennai".gcreddy."India".

x myDate=100 x=IsDate(myDate) msgbox x 'Output: False myDate="India" x=IsDate(myDate) msgbox x 'Output: False myDate=#10/05/2010# x=IsDate(myDate) msgbox x 'Output: True myDate=#10-05-2010# x=IsDate(myDate) msgbox x 'Output: True myDate=#10-05-10# x=IsDate(myDate) msgbox x 'Output: True myDate=10-05-2010 x=IsDate(myDate) msgbox x 'Output: False 8) DateDiff Function It provides difference between two dates. Date2. based on interval (day/month) Dim Date1.gcreddy@gcreddy.com 75 .com 7) IsDate It checks weather the given value is Date type data or not Examples: Dim myDate.gcreddy.x Date1=#10-10-2008# Date2=#10-09-2010# www.

date2) 'd for day msgbox x' It subtracts date1 from date2 x=DateDiff("m".gcreddy.x val="100" x=Isnumeric(val) msgbox x 'Output: True val=100 x=Isnumeric(val) msgbox x 'Output: True x=Isnumeric(500) msgbox x 'Output: True x=Isnumeric("India") msgbox x 'Output: False 10) Len Function It finds legngh of the String Example: Dim val.x val="Hyderabad" x=Len(val) www.gcreddy@gcreddy. we can day or month wise diffrence only. date1.com x=DateDiff("d".date2) 'it considers days only msgbox x' It subtracts date1 from date2 Note: through this function. date1.date2)' m for month msgbox x' It subtracts date1 from date2 x=DateDiff("y". date1. 9) IsNumeric It checks weather the given value is numeric or not and It provides True/False like Result Example: Dim val.com 76 .

Lengh) www.com msgbox x 'Output: 9 val=100 x=Len(val) msgbox x 'Output: 3 val="Hydera100" x=Len(val) msgbox x 'Output: 9 val="hy$@*de" x=Len(val) msgbox x 'Output: 7 val="100" x=Len(val) msgbox x 'Output: 3 val=#10-10-2010# x=Len(val) msgbox x 'Output: 10 x=Len("Krishna") msgbox x 'Output: 7 x=Len(Krishna) msgbox x 'Output: 0 x=Len() msgbox x 'Output: Error 11) Left Function Returns a specified number of charectors of a given string from left side Syntax: variable=Left(string.com 77 .gcreddy.gcreddy@gcreddy.

x val="Hyderabad" x=Right(val.3) msgbox x ' Output: 10/ 12) Right Function Returns a specified number of charectors of a given string from Right side Example: Dim val.x val="Hyderabad" x=Left(val.com Example: Dim val.1) msgbox x ' Output: 8 val="H92yderabad" x=Right(val.5) msgbox x ' Output: 92478 val=#10-10-10# x=Left(val.3) msgbox x ' Output: bad val="9247837478" x=Right(val.3) msgbox x ' Output: Hyd val="9247837478" x=Left(val.gcreddy@gcreddy.3) www.3) msgbox x ' Output: H92 x=Left(9247837478.1) msgbox x ' Output: 9 val="H92yderabad" x=Left(val.com 78 .gcreddy.

x val="Hyderabad" x=Mid(Val.1) msgbox x ' Output: H92yderabad x=Mid(9247837478.5.5) msgbox x ' Output: 37478 val=#10-10-10# x=Right(val.5) msgbox x ' Output: rabad val="9247837478" x=Mid(val.com msgbox x ' Output: bad x=Right(9247837478.com 79 .5) msgbox x ' Output: /2010 13) Mid function Returns a specified number of characters of a given string Example: Dim val.5) msgbox x ' Output: 0/2010 www.gcreddy.gcreddy@gcreddy.3) msgbox x ' Output: rab val="Hyderabad" x=Mid(Val.5) msgbox x ' Output: 37478 val="H92yderabad" x=Mid(val.6.5) msgbox x ' Output: 837478 val=#10-10-10# x=Mid(val.

x val="Hyderabad" x=StrReverse(val) msgbox x 'Output dabaredyH val="001" x=StrReverse(val) msgbox x 'Output: 100 val=1002 x=StrReverse(val) msgbox x 'Output: 2001 val=#10-10-10# x=StrReverse(val) msgbox x 'Output: 0102/01/01 x=StrReverse("Hyderabad") msgbox x 'Output: dabaredyH x=StrReverse(100) msgbox x 'Output: 001 15) StrComp Function It compares two string (Binary and textual) If a) Both are equal.gcreddy.com 80 . returns 0(zero) b) String 1 greater than string 2.com 14) StrReverse retuns reverse value of a string Example: Dim val. returns -1 www.gcreddy@gcreddy. returns 1(one) b) String 2 greater than string 1.

str2.gcreddy.str2.1) msgbox x 'Output 0 str1=100 str2=101 x=StrComp(str1.str2.com Example: Dim str1.1) msgbox x 'Output -1 str1="Indian" str2="India" x=StrComp(str1.str2.x str1="India" str2="India" x=StrComp(str1.1) msgbox x 'Output 1 str1=100 str2=100 x=StrComp(str1.1) msgbox x 'Output 0 str1="India" str2="Indian" x=StrComp(str1.1) msgbox x 'Output -1 str1="Indian" str2="Ndia" x=StrComp(str1.str2.str2.1) msgbox x 'Output 0 str1="india" str2="INDIA" x=StrComp(str1.com 81 .str2.gcreddy@gcreddy.str2.1) msgbox x 'Output -1 www.

x val="HYDERABAD" x=Ucase(val) msgbox x 'Output HYDERABAD val="Hyderabad" x=Ucase(val) msgbox x 'Output HYDERABAD www.gcreddy@gcreddy.com 16) Lcase function Coverts Upper case values into Lower case Dim val.x val="HYDERABAD" x=Lcase(val) msgbox x 'Output hyderabad val="Hyderabad" x=Lcase(val) msgbox x 'Output hyderabad val="HederabaD" x=Lcase(val) msgbox x 'Output hyderabad val="hyderabad" x=Lcase(val) msgbox x 'Output hyderabad x=Lcase("HYDERABAD") msgbox x 'Output hyderabad 17) Ucase function Coverts Lower case values into Upper case Example: Dim val.com 82 .gcreddy.

com val="HederabaD" x=Ucase(val) msgbox x 'Output HYDERABAD val="hyderabad" x=Ucase(val) msgbox x 'Output HYDERABAD x=Ucase("HYDERABAD") msgbox x 'Output HYDERABAD 18) Round Function Returns the round value of a given value if value decimal point above .49" x=Round(num) msgbox x 'Output: 14 num="Hyd" x=Round(num) msgbox x 'Output: Error 19) Trim Function Returns a copy of string without leading spaces www.gcreddy@gcreddy.5 it returns. next nearest value. Example: Dim num.x num=14. below .com 83 .49 x=Round(num) msgbox x 'Output: 14 num=14.5 returns before integer value.59 x=Round(num) msgbox x 'Output: 15 num="14.gcreddy.

com Dim val val=" msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x 20) Ltrim Function It removes spaces from left side of a string Dim val val=" msgbox x x=Len(x) msgbox x val="100 x=LTrim(val) " VB Script" x=LTrim(val) VB Script " 2#$%^" 100" VB Script" x=Trim(val) x=Trim(val) x=Trim(val) x=Trim(val) www.gcreddy@gcreddy.com 84 .gcreddy.

com 85 .gcreddy@gcreddy.com msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x val= msgbox x x=Len(x) msgbox x 21) Rtrim It removes spaces from right side of a string Dim val val="VB Script x=RTrim(val) msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x 100 " " 100 VB Script " 2#$%^ " x=LTrim(val) x=LTrim(val) x=LTrim(val) x=RTrim(val) www.gcreddy.

one-dimensional array containing a specified number of substrings Example: Dim a.b.gcreddy.gcreddy@gcreddy.Powerful.scripting.Language" a=Split(b.".") msgbox a(5) 'Output: Scripting b="VB Script is a Powerful scripting Language" www." ") x=IsArray(b) msgbox x 'Output: False x=IsArray(a) msgbox x 'Output: True msgbox a(6) 'Output: Language b="VB.a.is.x b="VB Script is a Powerful scripting Language" a=Split(b.Script.com val=" msgbox x x=Len(x) msgbox x val=" msgbox x x=Len(x) msgbox x val= msgbox x x=Len(x) msgbox x 2#$%^ " x=RTrim(val) VB Script " x=RTrim(val) 100 x=RTrim(val) 22) Split function Returns a zero-based.com 86 .

1 Case-sensitivity: By default.4 Parentheses: To achieve the desired result and to avoid errors. VBScript is not case sensitive and does not differentiate between uppercase and lower-case spelling of words."@") msgbox a(5) 'Output: Scripting b="VBScriptisaPowerfulscriptingLanguage" a=Split(b) msgbox a(5) 'Output: Error 12) VBScript syntax rules and guidelines 21.Page("Find a Flight:"). Note that the value 31 is also surrounded by quotation marks. the names of the Web site. it is important that we use parentheses () correctly in our statements.gcreddy@gcreddy. www. for example.WebList("toDay"). we must add quotation marks before and after the string.gcreddy. which also does not need quotation marks.3 Variables: We can specify variables to store strings. integers. For example. Web page. or constants.Select "31" browser("mercury").page("find a flight:"). The second argument (the value of the property) is a variable and therefore does not have quotation marks.Page("Find a Flight:"). in variables. Using variables helps to make our script more readable and flexible 21.select "31" 21. and edit box are all text strings surrounded by quotation marks.2 Text strings: When we enter a value as a text string.com a=Split(b) msgbox a(5) 'Output: Scripting b="VB@Script@is@a@Powerful@scripting@Language" a=Split(b.weblist("today"). In the following example. 2000) 21.com 87 .WaitProperty("items count". arrays and objects. only the property name (first argument) is a text string and is in quotation marks. Total_Items. in the above segment of script. because it is a text string that represents a number and not a numeric value. object and method names. The third argument (specifying the timeout) is a numeric value. the two statements below are identical in VBScript: Browser("Mercury"). For example. Browser("Mercury").

6 Comments: We can add comments to our statements using an apostrophe (').com 88 .com 21. VBScript syntax errors occur during the program compilation stage.2 VBScript Syntax Errors VBScript syntax errors are errors that result when the structure of one of our VBScript statements violates one or more of the grammatical rules of the VBScript scripting language. and memory is being dynamic allocated. 13.gcreddy. 21. before the program has begun to be executed. to make our scripts easier to understand and maintain. they are VBScript Run-time Errors and VBScript Syntax Errors 13.7 Spaces: We can add extra blank spaces to our script to improve clarity. www.5 Indentation: We can indent or outdent our script to reflect the logical structure and nesting of the statements. 21. It is recommended that we add comments wherever possible. These spaces are ignored by VBScript.1 VBScript Run-time Errors VBScript run-time errors are errors that result when our VBScript script attempts to perform an action that the system cannot execute. when variable expressions are being evaluated. either at the beginning of a separate line. 13) Errors We have two types Errors in VB Script.gcreddy@gcreddy. VBScript run-time errors occur while our script is being executed. or at the end of a statement.

FileSystemObject") oFSO. however. or our data access requirements may not call for the extra functionality associated with a fullfeatured database. if not creating the folder www. method syntax with a rich set of properties. contained in the Scripting type library (Scrrun. True 4) Checking weather the folder available or not.gcreddy@gcreddy. supports the creation and manipulation of text files through the TextStream object. such as their names and the date they were created or last modified. The FSO model gives our application the ability to create.CopyFolder "E:\gcr". the FSO model does not support binary files.dll).DeleteFolder("E:\Gcreddy") 3) Copying Folders Set oFSO=createobject("Scripting. use the FileOpen Function with the Binary keyword. objFolder. When processing files.com File System Operations File System Object Model: The File System Object (FSO) model provides an object-based tool for working with folders and files.com 89 .CreateFolder(strDirectory) 2) Delete a Folder Set oFSO = CreateObject("Scripting. "C:\jvr". The FSO model. storing our data in a text file or binary file is the most efficient solution. or to determine if and where particular folders exist. We may not want to have such overhead. doing so adds a significant amount of overhead to our application. It also enables us to get information about folders. and delete folders. In this case. move. It allows us to use the familiar object. easy-to-access format.FileSystemObject") Set objFolder = objFSO. We can also employ the traditional Visual Basic statements and commands.Filesystemobject") oFSO. The FSO model makes processing files much easier as well. strDirectory strDirectory = "D:\Gcreddy" Set objFSO = CreateObject("Scripting. Although we can store data in a database. our primary goal is to store data in an efficient. alter. and output (read) the data. Examples 1) Create a Folder Option Explicit Dim objFSO.gcreddy. We need to be able to create files. methods. insert and change the data. To manipulate binary files. and events to process folders and files.

gcreddy. objFolder.FileExists(strDirectory & strFile) Then Set objFolder = objFSO.com 90 .txt") End if 9) Reading Data character by character from a Flat File Set objFSO = CreateObject("Scripting.CreateTextFile("E:\Gcreddy.Read(1) msgbox strCharacters Loop www.OpenTextFile("E:\Gcreddy.CreateFolder(strDirectory) end if 5) Returning a collection of Disk Drives Set oFSO = CreateObject("Scripting.txt") 8) Checking weather the File is available or not.FileSystemObject") If objFSO.GetFolder(strDirectory) msgbox strDirectory & " already created " else Set objFolder = objFSO.DriveLetter Next 6) Getting available space on a Disk Drive Set oFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.txt".com Option Explicit Dim objFSO. if not creating the File strDirectory="E:\" strFile="Gcreddy.AvailableSpace 7) Creating a Flat File Set objFSO = CreateObject("Scripting.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") Set oDrive = oFSO.FileSystemObject") If objFSO.CreateTextFile("E:\Gcreddy.GetDrive("C:") MsgBox "Available space: " & oDrive. 1) Do Until objFile.FileSystemObject") Set objFile = objFSO.FileSystemObject") Set colDrives = oFSO.Drives For Each oDrive in colDrives MsgBox "Drive letter: " & oDrive.FolderExists(strDirectory) Then Set objFolder = objFSO.gcreddy@gcreddy.AtEndOfStream strCharacters = objFile. strDirectory strDirectory = "D:\Gcreddy" Set objFSO = CreateObject("Scripting.GetFolder(strDirectory) Else Set objFile = objFSO.

skipline While myfile.exe".FileSystemObject") If objFSO.Close SET WriteStuff = NOTHING SET myFSO = NOTHING 13) Delete a text file Set objFSO=createobject("Scripting.gcreddy.com 10) Reading Data line by line from a Flat File Set objFSO = CreateObject("Scripting.myfile Set fso=createobject("scripting.GetFile("E:\gcr.OpenTextFile("e:\Gcreddy.filesystemobject") Set txtFilepath = objFSO.readline s=split (x.1) myfile.Close Wend 12) Writing data to a text file Dim Stuff.filesystemobject") Set myfile= fso. WriteStuff. if available delete the File strDirectory="E:\" strFile="gcr.txt".Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.Click Window("Flight Reservation").FileSystemObject") Set objFile = objFSO.") SystemUtil.Set s(0) Dialog("Login").FileExists(strDirectory & strFile) Then www.WinButton("OK").txt".WinEdit("Agent Name:").com 91 . dateStamp dateStamp = Date() Stuff = "I am Preparing this script: " &dateStamp Set myFSO = CreateObject("Scripting. ". True) WriteStuff.FileSystemObject") Set WriteStuff = myFSO.WriteLine(Stuff) WriteStuff.AtEndOfStream strCharacters = objFile.opentextfile ("F:\Gcreddy."C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\".OpenTextFile("E:\Gcreddy.WinEdit("Password:").Activate Dialog("Login").atendofline <> True x=myfile.SetSecure s(1) Dialog("Login")."open" Dialog("Login").Delete() 14) Checking weather the File is available or not. 8.gcreddy@gcreddy. myFSO."".txt" Set objFSO = CreateObject("Scripting. 1) Do Until objFile.txt") txtFilepath.txt".Readline msgbox strCharacters Loop 11) Reading data from a flat file and using in data driven testing Dim fso.

0) Set File2 = FS.GetFile(FilePath1).FileSystemObject") Set oTxtFile = oFso. sReadTxt.OpenAsTextStream(1. File1.Getfile(strDirectory & strFile) objFile.delete () End if 15) Comparing two text files Dim f1. oTxtFile.Size Then CompareFiles = True Exit Function End If Set File1 = FS. f2 f1="e:\Gcreddy1. FOR_READING) sReadTxt = oTxtFile.gcreddy@gcreddy. Str2. 0) If CompareFiles <> 0 Then CompareFiles = True Exit Do End If Loop File1.Close() End Function Call Comparefiles(f1.txt" f2="e:\Gcreddy2.GetFile(FilePath2).com Set objFile = objFSO.Execute(sReadTxt) MatchesFound = oMatches. oMatches Set oFso = CreateObject("Scripting." End If 16) Counting the number of times a word appears in a file sFileName="E:\gcr.OpenAsTextStream(1.Read Str2 = File2.com 92 .Pattern = sString oRegEx.Close() File2.OpenTextFile(sFileName." Else MsgBox "Files are different.Count www. File2 Set FS = CreateObject("Scripting.ReadAll Set oRegEx = New RegExp oRegEx.AtEndOfStream = False Str1 = File1.IgnoreCase = bIgnoreCase oRegEx.Size <> FS.txt" Public Function CompareFiles (FilePath1. 0) CompareFiles = False Do While File1. f2) = False Then MsgBox "Files are identical. FilePath2) Dim FS.GetFile(FilePath2).GetFile(FilePath1).txt" sString="gcreddy" Const FOR_READING = 1 Dim oFso.f2) If CompareFiles(f1. oRegEx.Read CompareFiles = StrComp(Str1.Global = True Set oMatches = oRegEx.FileSystemObject") If FS.gcreddy.

HDR=YES.Echo "Server name: " & arrServiceList(0) For i = 1 to Ubound(arrServiceList) Wscript.Item("Department") Wscript.Fields.Open "Provider=Microsoft.gcreddy. adLockOptimistic.AtEndOfStream strNextLine = objTextFile.") Wscript.com 93 .FMT=Delimited""" objRecordset.txt". ".Recordset") strPathtoTextFile = "C:\Databases\" objConnection.Connection") Set objRecordSet = CreateObject("ADODB.Fields.FileSystemObject") Set objTextFile = objFSO. adCmdText Do Until objRecordset. ForReading) Do Until objTextFile." & _ "Data Source=" & strPathtoTextFile & ".com Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing msgbox MatchesFound 17) Read a CSV File Using Database Techniques On Error Resume Next Const adOpenStatic = 3 Const adLockOptimistic = 3 Const adCmdText = &H0001 Set objConnection = CreateObject("ADODB.4.OLEDB.Echo "Service: " & arrServiceList(i) Next Loop www.Readline arrServiceList = Split(strNextLine .Jet.Open "SELECT * FROM PhoneList.Fields." & _ "Extended Properties=""text.Echo "Extension: " & objRecordset.EOF Wscript.0.Echo "Name: " & objRecordset.csv".OpenTextFile _ ("e:\gcreddy.Item("Extension") objRecordset.MoveNext Loop 18) Read a Text File into an Array Const ForReading = 1 Set objFSO = CreateObject("Scripting. adOpenStatic.gcreddy@gcreddy.Echo "Department: " & _ objRecordset. _ objConnection.Item("Name") Wscript.

"C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\". 1).WinEdit("Password:").worksheets("Sheet1") 4) Rows_Count=mySheet.open ("C:\Documents and Settings\admin\My Documents\gcreddy.UsedRange If cell.SetSecure pwd 12) Dialog("Login").Application") objExcel.Set Agent 11) Dialog("Login").Open("E:\gcreddy2. enter some data and save the file through VB scripting? 1) 2) 3) 4) 5) 6) 7) Dim objexcel Set objExcel = createobject("Excel.ActiveWorkbook.application") objexcel.com Excel File Operations 1) Create an Excel file.Workbooks.Worksheets(1) Set objWorksheet2= objWorkbook2.close objWorkbook2.Application") 2) Set myFile=myExcel."B") 8) SystemUtil.exe".workbooks."A") 7) pwd=mySheet.xls") Set objWorkbook2= objExcel.Cells(i.WinEdit("Agent Name:").gcreddy.Workbooks.Quit 2) Data Driven Testing through an External Excel Sheet 1) Set myExcel=Createobject("Excel.com 94 .usedrange.Cells(1.add objexcel.Visible = True objexcel.Value Then msgbox "value is different" Else msgbox "value is same" End If Next objWorkbook1.gcreddy@gcreddy."".WinEdit("Password:").Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.SaveAs("f:\exceltest.Workbooks.close www.Value = "Testing" objexcel.rows.Open("E:\gcreddy1.xls") 3) Set mySheet=myFile.xls") Set objWorksheet1= objWorkbook1.Visible = True Set objWorkbook1= objExcel.Value <> objWorksheet2.Activate 10) Dialog("Login")."open" 9) Dialog("Login").cells(i.count 5) For i= 1 to Rows_Count 6) Agent=mySheet.xls") objexcel.Type micReturn 13) Window("Flight Reservation").Range(cell.Worksheets(1) For Each cell In objWorksheet1.Close 14) Next 3) Compare two excel files Set objExcel = CreateObject("Excel.Address).

AddSheet "gcreddy" Datatable.WinEdit("Agent Name:").AddSheet "gcreddy" Datatable.GetROProperty ("text") If eres=ares Then datatable("res".Open("C:\Scripts\gcreddy.Close Next Example 2): Datatable.Application") Set objWorkbook = objExcel.VbEdit("res").3) VbWindow("Form1").xls".Click eres= Datatable.Workbooks.3 n=datatable.VbButton("ADD").Set datatable("pwd".3) Dialog("Login").quit set objExcel=nothing 4) Data Driven Testing using Data Table methods Datatable.Activate VbWindow("Form1").WinButton("OK").ImportSheet "C:\Documents and Settings\Administrator\Desktop\gcreddy.VbEdit("val1").gcreddy.com 95 .VbEdit("val2").SetCurrentRow(i) Invokeapplication "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.GetRowCount For i= 1 to n Datatable.ImportSheet "C:\Documents and Settings\Administrator\Desktop\gcreddy.Application") Set objWorkbook = objExcel.Set datatable("V2".SetCurrentRow(i) VbWindow("Form1").3) Dialog("Login").Set datatable("agent".GetSheet (3).exe" Dialog("Login").Click Window("Flight Reservation").xls") 6) Read an Excel Spreadsheet Set objExcel = CreateObject("Excel.1.gcreddy@gcreddy.Value ("res".1.Workbooks.3 n=datatable.Open _ www.GetRowCount For i= 1 to n Datatable.WinEdit("Password:").Set datatable("V1".xls".GetSheet (3).3) VbWindow("Form1").3) ares=VbWindow("Form1").3)=pass else datatable("res".com objExcel.Activate Dialog("Login").3)=fail End If Next 5) Open an Excel Spreadsheet Set objExcel = CreateObject("Excel.

("C:\Scripts\New_users.xls") intRow = 2 Do Until objExcel.Cells(intRow,1).Value = "" Wscript.Echo "CN: " & objExcel.Cells(intRow, 1).Value Wscript.Echo "sAMAccountName: " & objExcel.Cells(intRow, 2).Value Wscript.Echo "GivenName: " & objExcel.Cells(intRow, 3).Value Wscript.Echo "LastName: " & objExcel.Cells(intRow, 4).Value intRow = intRow + 1 Loop objExcel.Quit 7) Add Formatted Data to a Spreadsheet Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.Workbooks.Add objExcel.Cells(1, 1).Value = "Test value" objExcel.Cells(1, 1).Font.Bold = TRUE objExcel.Cells(1, 1).Font.Size = 24 objExcel.Cells(1, 1).Font.ColorIndex = 3 8) Sort an Excel Spreadsheet on Three Different Columns Const xlAscending = 1 Const xlDescending = 2 Const xlYes = 1 Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True Set objWorkbook = _ objExcel.Workbooks.Open("C:\Scripts\Sort_test.xls") Set objWorksheet = objWorkbook.Worksheets(1) Set objRange = objWorksheet.UsedRange Set objRange2 = objExcel.Range("A1") Set objRange3 = objExcel.Range("B1") Set objRange4 = objExcel.Range("C1") objRange.Sort objRange2,xlAscending,objRange3,,xlDescending, _ objRange4,xlDescending,xlYes




Database Operations
ADO (Active Data Objects), this technology allows users to access data easily from many existing databases (such as Access or Paradox) or from ODBC compliant databases like Oracle or MS SQL Server. Using ADO is quite simple and allows programmers to provide flexible database front ends to users that are reliable and include many features. Following are some of the key objects found in the ADO object model and some of their key methods and properties. Connection Object This object represents an open connection to the data source. This connection can be a local connection (say App.Path) or can be across a network in a client server application. Some of the methods and properties of this object are not available depending on the type of data source connected to. Command Object A command object specifies a specific method we intend to execute on or against the data source accessed by an open connection. RecordSet Object The RecordSet object represents a complete set of records from an executed command or from an underlying base table in the database. A key thing to note is that a RecordSet object references only one record at a time as the current record. Examples 1) Get Test Data from a Database and use in Data Driven Testing (through Scripting) 1) Dim con,rs 2) Set con=createobject("Adodb.connection") 3) Set rs=createobject("Adodb.recordset") 4) con.provider=("microsoft.jet.oledb.4.0") 5) con.open "C:\Documents and Settings\Administrator\My Documents\Gcreddy.mdb" 6) rs.open "Select * From Login",con 7) While rs.eof <>True 8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe" 9) Dialog("Login").Activate 10) Dialog("Login").WinEdit("Agent Name:").Set rs.fields ("Agent") 11) Dialog("Login").WinEdit("Password:").Set rs.fields ("Password") 12) Dialog("Login").WinButton("OK").Click 13) Window("Flight Reservation").Close 14) rs.movenext 15) Wend




2) Exporting Data from a Database to an Excel Sheet 1) Dim con,rs 2) Set con=createobject("adodb.connection") 3) Set rs=createobject("adodb.recordset") 4) con.provider="microsoft.jet.oledb.4.0" 5) con.open"C:\Documents and Settings\admin\My Documents\Gcreddy.mdb" 6) rs.open"select*from Login",con 7) Set ex=createobject("Excel.Application") 8) Set a=ex.workbooks.open("C:\Documents and Settings\admin\My Documents\Gcreddy.xls") 9) Set b=a.worksheets("sheet1") 10) i=1 11) Do While Not rs.EOF 12) b.cells (i,1).value=rs.fields("agent") 13) b.cells(i,2).value=rs.fields("password") 14) rs.movenext 15) i=i+1 16) Loop 17) a.save 18) a.close 3) Exporting Data from a Database to a Text file Dim objCon,objRs,ObjFso,myFile,myData,rc,r Set objCon=createobject("Adodb.connection") Set objRs=createobject("Adodb.Recordset") set objFso=createobject("Scripting.Filesystemobject") Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr\My Documents\gcreddy.txt",8) objcon.provider=("Microsoft.jet.oledb.4.0") objcon.open"C:\Documents and Settings\gcr\My Documents\gcreddy.mdb" objrs.open "select * from login",objCon r=1 Do until objRs.EOF a=objRs.Fields ("Agent") b=objRs.Fields ("Pwd") myFile.Writeline a &","& b r=r+1 objRs.MoveNext Loop myFile.Close objCon.Close 4) Connecting to a SQL Sever database Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset")



Open "SELECT * FROM Storage Where ComputerName = 'Computer1'".Data Source=atl-sql-01.MoveFirst objRecordSet2.com 99 .fabrikam\kenmyer.Password=34DE6t4G!.gcreddy. _ objConnection." & _ "User ID=fabrikam\kenmyer.Recordset") objConnection.Echo objRecordSet. adOpenStatic. adOpenStatic. adOpenStatic.Open _ "Northwind.Initial Catalog=Northwind.4.OLEDB. _ objConnection.RecordCount 5) Open a Database Using a DSN Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB." & _ "Trusted_Connection=Yes. " & _ "Data Source=inventory.com objConnection. adLockOptimistic objRecordSet.Open "SELECT * FROM Customers".Open _ "Provider=SQLOLEDB. _ objConnection. _ objConnection.0.gcreddy@gcreddy.Connection") Set objRecordSet = CreateObject("ADODB.34ghfn&!j" objRecordSet. adLockOptimistic objRecordSet. adLockOptimistic www. adOpenStatic.RecordCount 6) Open Two Record sets Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Open "SELECT * FROM Customers". adLockOptimistic objRecordSet.Open "SELECT * FROM GeneralProperties Where ComputerName = 'Computer1'".MoveFirst Wscript.Open _ "Provider= Microsoft." objRecordSet.mdb" objRecordSet.Jet.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") Set objRecordSet2 = CreateObject("ADODB.MoveFirst Wscript.Echo objRecordSet.Recordset") objConnection.

Jet.OLEDB.Echo objRecordset.EOF Wscript.com objRecordSet2.4.Open "SELECT * FROM EventTable " & _ "WHERE Type = 'Error'".Fields. _ objRecordset2.open"Provider=Microsoft.ActiveConnection=objCon www.Recordset") objConnection.MoveFirst Wscript.objCom Set objCon=Createobject("ADODB.Item("OSName") objRecordSet.OLEDB.gcreddy.mdb.MoveNext Loop objRecordSet.Echo "Number of records: " & objRecordset.Command") objCom.com 100 . objConnection.EOF Wscript.Close objRecordSet2.Fields. adOpenStatic.MoveNext Loop Do Until objRecordset2.0.Data Source=C:\gcreddy.Item("DriveDescription") objRecordSet2.Echo objRecordset.Fields.Close objConnection.mdb" objRecordSet. " & _ "Data Source = eventlogs.Close objConnection.Connection") Set objRecordSet = CreateObject("ADODB.Close 7) Searching a Database Using String Criteria Const adOpenStatic = 3 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Item("DriveName").connection") objCon." Set objCom=Createobject("ADODB.Open _ "Provider = Microsoft.Close 8) Insert Data into a database table using Database Command Object Dim objCon.Fields.Jet.Item("ComputerName") Wscript.gcreddy@gcreddy. _ adLockOptimistic objRecordSet.MoveFirst Do Until objRecordset.Echo objRecordset2.0.4.RecordCount objRecordSet.

CommandText="insert into Emp values( '"&strEmpName&" '.Data Source=C:\gcreddy."input" intRowcount=Datatable.OLEDB." Set objCom=Createobject("ADODB.0."&intEmpNo&".CommandText="insert into Emp values('G C Reddy'.intRowcount.88233.intEmpSal.Jet.Value(1.Command") objCom.strEmpName.connection") objCon.com 101 .com objCom.i Set objCon=Createobject("ADODB.GetSheet("input").Close Set objCom=Nothing Set objCon=Nothing www."input") intEmpSal= DataTable.ActiveConnection=objCon Datatable.mdb.Value(3."input") objCom.xls".Value(2.Execute objCon.SetCurrentRow(i) strEmpName= DataTable.objCom.gcreddy."&intEmpSal&")" objCom.ImportSheet "C:\gcreddy.gcreddy@gcreddy.1.30000)" objCom.Execute Next objCon.open"Provider=Microsoft."input") intEmpNo= DataTable.4.intEmpNo.AddSheet("input") Datatable.GetRowCount Msgbox intRowcount For i=1 to intRowcount step 1 DataTable.Close Set objCom=Nothing Set objCon=Nothing 9) Insert multiple sets of Data (using Excel sheet) into a database table using Database Command Object Dim objCon.

if it feels sufficient then it stops learning otherwise. If it feels sufficient. in smart identification 2 types of properties available. It learns first assistive property and once again stops and thinks.com 102 . and then we configure Smart Identification for that object. if we feel that configuration is not sufficient for recognizing objects in our application. www. At the end of assistive properties list also if it feels not satisfied and it finally goes to Ordinal Identifier. like this qtp learns one by one.gcreddy.com Object Identification Configuration Overview: Generally for every object 20-25 properties information available. After normal identification if qtp feels not satisfied then it goes to smart identification. then it stops learning otherwise it goes Optional Filter Properties and learns one by one. QTP learns information in the following in case of Smart Identification: Smart identification is an optional feature. we can configure some more Object Identification Types a) 1) 2) b) 1) 2) c) Normal identification Mandatory properties Assistive properties Smart identification base filter properties optional filter properties Ordinal identifier 1) 2) 3) location index creation time(only for web) QTP learns information in the following in case of normal identification: First of all the qtp learns all the mandatory properties at a time and thinks whether these properties sufficient to identify the object uniquely. if we feel normal identification is not sufficient for any object. Still it feels not satisfied finally it goes to Ordinal Identifier. Qtp has default object identification configuration for every environment.gcreddy@gcreddy. in order to avoid Ordinal Identifier. qtp recognizes object using 2 0r 3 important properties. first qtp learns all base filter properties at a time and thinks whether these properties are sufficient for identifying the object uniquely.

1.com 103 . qtp generates 0.2 like numbers. QTP is providing a special feature called "Generate Script". index starts from zero 3) Creation time: it is based on loading time of the web objects.location starts from zero.gcreddy@gcreddy.com Ordinal identifiers: There are 3 types of ordinal identifiers available 1) Location: is based on object location in the AUT . 2) index: it is based on sequence of the programs. STEPS: 1) Settings available in 3 areas. NOTE: After executing these scripts all team members can get same settings. a) File->Settings b) Tools->Options c) Tools->Object Identification 2) Perform required settings and generate Scripts 3) Share Script files to team members and ask them to execute those scripts. www.gcreddy.making Tool settings globally is not possible. For making tool settings global. Tool Settings Globalization: As QTP is a I-tier(Stand-alone) application.

For XML checkpoints we can set attribute or element values as regular expressions. They are often used within matching. an Environment parameter value. Ways of Regular Expressions: a) Backslash Character: A backslash (\) can serve two purposes. searching or replacing algorithms. Regular Expressions in QTP: Regular expressions can be used in QTP for identifying objects and text strings with varying values. or a property value in Descriptive programming. w. when creating a text checkpoint to check that a varying text string is displayed on our application. such as the letters n. Ex: www. It can be used in conjunction with a special character to indicate that the next character be treated as a literal character. Where we use: o Defining the property values of an object in Descriptive programming for handling dynamic objects o For parameterizing a step o creating checkpoints with varying values Using Regular Expressions in QTP: We can define a regular expression for a constant value. we can set the expected value of an object's property as a regular expression so that an object with a varying value can be verified. or d. a Data Table parameter value.com 104 .) instructs QTP to search for any single character (except for \n). the combination indicates a special character.gcreddy@gcreddy. t. if the backslash (\) is used in conjunction with some characters that would otherwise be treated as literal characters. b) Matching Any Single Character: A period (.gcreddy. We can define a regular expression in standard checkpoint to verify the property values of an object.com Regular Expressions in QTP What is Regular Expression? It is a way of representing data using symbols. Alternatively. We can define the text string as a regular expression.

or welcome followed by a space or any other single character.com welcome. e) Matching Any Single Character within a Range: To match a single character within a range. enter: 186[789] d) Matching Any Single Character Not in a List: When a caret (^) is the first character inside square brackets.gcreddy@gcreddy. 1868. www. Example: [^ab] Matches any character except a or b. Example: For matching any year in the 2010s. welcomed. c) Matching Any Single Character in a List: Square brackets instruct QTP to search for any single character within a list of characters. but not cr. Ex: To search for the date 1867. caaaaaar. or 1869. and cr g) Matching One or More Specific Characters: A plus sign (+) instructs QTP to match one or more occurrences of the preceding character. For example: ca*r Matches car.com 105 . we can use square brackets ([ ]) with the hyphen (-) character.gcreddy. Matches welcomes. it instructs QTP to match any character in the list except for the ones specified in the string. For example: ca+r Matches car and caaaaaar. enter: 201[0-9] f) Matching Zero or More Specific Characters: An asterisk (*) instructs QTP to match zero or more occurrences of the preceding character.

gcreddy. but nothing else. m) Matching Any AlphaNumeric Character Including the Underscore: \w instructs QTP to match any alphanumeric character and the underscore (A-Z. or before a newline character. or after a newline character.gcreddy@gcreddy. 0-9. k) Matching the Beginning of a Line: A caret (^) instructs QTP to match the expression only at the start of a line. o) Combining Regular Expression Operators: We can combine regular expression operators in a single expression to achieve the www. just as in mathematics and programming languages. Using groups is especially useful for delimiting the argument(s) to an alternation operator ( | ) or a repetition operator ( * . l) Matching the End of a Line: A dollar sign ($) instructs QTP to match the expression only at the end of a line.com h) Matching Zero or One Specific Character: A question mark (?) instructs QTP to match zero or one occurrences of the preceding character. j) Matching One of Several Regular Expressions: A vertical line (|) instructs QTP to match one of a choice of expressions. ? . { } ).com 106 . + . For example: ca?r Matches car and cr. az. i) Grouping Regular Expressions: Parentheses (()) instruct QTP to treat the contained sequence as a unit. n) Matching Any Non-AlphaNumeric Character: \W instructs QTP to match any character other than alphanumeric characters and underscores. _).

starter.com exact search criteria we need. or 4 digits between 1000-1200. start.gcreddy@gcreddy. It provides simple support for defining regular expressions.* Matches start. we can use a combination of brackets and an asterisk to limit the search to a combination of non-numeric characters. For example. and so forth. Regular Expression Object Properties and Methods: Properties: a) Global Property b) IgnoreCase Property c) Pattern Property Methods: a) Execute Method b) Replace Method www. 3 digits. For example: [a-zA-Z]* To match any number between 0 and 1200. started.com 107 . The regular expression below matches any number between 0 and 1200.gcreddy. starting. ([0-9]?[0-9]?[0-9]|1[01][0-9][0-9]|1200) RegExp object VB Script is providing RegExp object for defining Regular expressions. 2 digits. we need to match numbers with 1 digit.

Echo "At position " & objMatch.Pattern = WScript.com c) Test Method Regular Expressions Examples: 1) Match File Names in a Directory against Regular Expression Set objFS = CreateObject("Scripting.gcreddy.Name) If bMatch Then WScript.Echo strFileContents objTS.Global = True objRE.Files Set objRE = New RegExp objRE.Name End If Next 2) Match Content in a File against a Regular Expression strFileName = "E:\gcreddy.Echo vbNewLine & "Resulting Matches:" For Each objMatch In colMatches WScript.Global = True objRE.gcreddy@gcreddy.txt" Set objFS = CreateObject("Scripting.Pattern = WScript.Shell") strCurrentDirectory = objShell.GetFolder(strCurrentDirectory) Set colFiles = objFolder.com 108 .ReadAll WScript.CurrentDirectory Set objFolder = objFS.IgnoreCase = False objRE.Close Set objRE = New RegExp objRE.OpenTextFile(strFileName) strFileContents = objTS.FileSystemObject") Set objShell = CreateObject("WScript.FirstIndex & " matched " & objMatch.FileSystemObject") Set objTS = objFS.Value -------------------------------------------------- www.Echo "Searching Within: " WScript.Echo objFile.Arguments(0) Set colMatches = objRE.Arguments(0) For Each objFile In colFiles bMatch = objRE.IgnoreCase = False objRE.Execute(strFileContents) WScript.Test(objFile.

QTP has provided a separate Tool called 'Test Batch Runner'. Run or Execute Test Batches from Test Batch Runner. Running or Executing a Test Batch Open Test Batch Runner Tool Navigation: File>open>browse path of the test batch>batch>run Note: Test Batch Runner launches QTP Tool. www. For performing Batch Testing.com Batch Testing Executing a group of tests/series of tests at a time is known as Batch Testing or Batch Execution. Create Individual Tests and Run once.com 109 .gcreddy. Steps for Batch Testing: 1). Open 'Test batch Runner' Tool and Form Batches. 3) Provide permission to 'Test batch Runner' to run tests 4). Navigation: Start>program>quicktest professional>Tools>Test Batch Runner>File>new>batch>add>browse path of the test (like this add number of tests)>save with MTB extension (Module test batche)>close test batch runner. 5) View Test wise Result in 'Test Result Viewer' Forming a Test Batch: Launch Test Batch Runner.gcreddy@gcreddy. 2). QTP runs Tests one by one. Navigation: Tools>Options>Run>check allow other mercury products>apply & Ok Executing partial Test Batch Open Test Batch Runner >open Test Batch>Select or deselect tests>run test batch. Note: Allowing other products to Run Tests.

"Bangalore" www.gcreddy. and are stored in the array. item pairs.Add "b". "Hyderabad" cities. A Dictionary object is the equivalent of a PERL associative array/Hash Variable. Example: Dim cities Set cities = CreateObject("Scripting.com VB Script Other Objects 1) Dictionary Object Dictionary Object that stores data key. false if it does not. RemoveAll Method The RemoveAll method removes all key. The key is used to retrieve an individual item and is usually an integer or a string. Keys Method Returns an array containing all existing keys in a Dictionary object. Each item is associated with a unique key. item pair from a Dictionary object.Dictionary") Dictionary Objects Methods: Add Method Adds a key and item pair to a Dictionary object Exists Method Returns true if a specified key exists in the Dictionary object. but can be anything except an array.Dictionary") cities. Items Method Returns an array containing all the items in a Dictionary object. Items can be any form of data.com 110 . Remove Method Removes a key.Add "h". Creating a Dictionary Object: Set objDictionary = CreateObject("Scripting. item pairs from a Dictionary object.gcreddy@gcreddy.

Add "Printer 2".Dictionary") objDictionary.Add "c". Read/write.Keys Wscript. "Offline" objDictionary. Key Property Sets a key in a Dictionary object.Add "Printer 3". For collections. returns an item based on the specified key.Add "Printer 3".Add "Printer 1".Echo "First run: " For Each strKey in colKeys     Wscript. CompareMode Property Sets and returns the comparison mode for comparing string keys in a Dictionary object.Add "Printer 2". "Printing" colKeys = objDictionary. Item Property Sets or returns an item for a specified key in a Dictionary object.com 111 . Read-only. Examples: 1)  Add  Elements to a Dictionary Set objDictionary = CreateObject("Scripting.Echo strKey Next objDictionary. "Printing"    objDictionary. "Offline" objDictionary.Dictionary") objDictionary.com cities.Add "Printer 1". "Printing"    objDictionary.gcreddy@gcreddy. "Chennai" Dictionary Objects Properties: Count Property Returns the number of items in a collection or Dictionary object.gcreddy. "Printing" 2) Delete All Elements from Dictionary Set objDictionary = CreateObject("Scripting.Keys www.RemoveAll colKeys = objDictionary.

Remove("Printer 2") colKeys = objDictionary. "Printing" colKeys = objDictionary.Echo strKey Next www.com Wscript. "Printing" objDictionary.Echo VbCrLf & "Second run: " For Each strKey in colKeys     Wscript.com 112 .Echo strKey Next objDictionary.Echo strKey Next 3) Delete One Element from a Dictionary Set objDictionary = CreateObject("Scripting.gcreddy.Add "Printer 2".Add "Printer 1".gcreddy@gcreddy.Echo VbCrLf & "Second run: " For Each strKey in colKeys Wscript.Keys Wscript.Add "Printer 3".Echo "First run: " For Each strKey in colKeys Wscript.Dictionary") objDictionary. "Offline" objDictionary.Keys Wscript.

4) List the Number of Items in a Dictionary Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing"    objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" Wscript.Echo objDictionary.Count 5) Verify the Existence of a Dictionary Key Set objDictionary = CreateObject("Scripting.Dictionary") objDictionary.Add "Printer 1", "Printing" objDictionary.Add "Printer 2", "Offline" objDictionary.Add "Printer 3", "Printing" If objDictionary.Exists("Printer 4") Then Wscript.Echo "Printer 4 is in the Dictionary." Else Wscript.Echo "Printer 4 is not in the Dictionary." End If 2) RegExp object

VB Script is providing RegExp object for defining Regular expressions, It provides simple support for defining regular expressions. Regular Expression Object Properties and Methods: Properties: a) Global Property b) IgnoreCase Property c) Pattern Property Methods: a) Execute Method




b) Replace Method c) Test Method

1) Match File Names in a Directory against Regular Expression

Set objFS = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("WScript.Shell") strCurrentDirectory = objShell.CurrentDirectory

Set objFolder = objFS.GetFolder(strCurrentDirectory) Set colFiles = objFolder.Files

Set objRE = New RegExp objRE.Global = True

objRE.IgnoreCase = False objRE.Pattern = WScript.Arguments(0)

For Each objFile In colFiles bMatch = objRE.Test(objFile.Name) If bMatch Then WScript.Echo objFile.Name End If Next



2) Match Content in a File against a Regular Expression strFileName = "E:\gcreddy.txt" Set objFS = CreateObject("Scripting.FileSystemObject")

Set objTS = objFS.OpenTextFile(strFileName) strFileContents = objTS.ReadAll WScript.Echo "Searching Within: " WScript.Echo strFileContents objTS.Close

Set objRE = New RegExp objRE.Global = True

objRE.IgnoreCase = False objRE.Pattern = WScript.Arguments(0)

Set colMatches = objRE.Execute(strFileContents) WScript.Echo vbNewLine & "Resulting Matches:" For Each objMatch In colMatches WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value Next 3) Database Command Object 1) Insert Data into a database table using Database Command Object Dim objCon,objCom Set objCon=Createobject("ADODB.connection") objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;" Set objCom=Createobject("ADODB.Command")



com 116 .CommandText="insert into Emp values( '"&strEmpName&" '."input" intRowcount=Datatable.intEmpNo.OLEDB."input") intEmpNo= DataTable.Close Set objCom=Nothing Set objCon=Nothing 2) Insert multiple sets of Data (using Excel sheet) into a database table using Database Command Object Dim objCon."&intEmpNo&".GetRowCount Msgbox intRowcount For i=1 to intRowcount step 1 DataTable.0."input") objCom.Add mw.i Set objCon=Createobject("ADODB.typetext "hello" mw.connection") objCon.ActiveConnection=objCon objCom.CommandText="insert into Emp values('G C Reddy'."input") intEmpSal= DataTable.quit set mw=nothing www.Value(1.4.gcreddy.xls".AddSheet("input") Datatable." Set objCom=Createobject("ADODB.30000)" objCom.selection.gcreddy@gcreddy.intEmpSal.objCom.1.mdb.ActiveConnection=objCon Datatable.open"Provider=Microsoft.intRowcount.ImportSheet "C:\gcreddy.Close Set objCom=Nothing Set objCon=Nothing 4) Word Object 1) Create a word document and write some data dim mw set mw=CreateObject("Word.SetCurrentRow(i) strEmpName= DataTable.GetSheet("input").Data Source=C:\gcreddy.Value(3.Jet.Value(2.doc" mw.Execute Next objCon.88233.Execute objCon.Documents.strEmpName.Application") mw.com objCom.SaveAs "e:\gcreddy."&intEmpSal&")" objCom.ActiveDocument.Command") objCom.

Close(False) next mw.FileName="*.FileSearch.value="Link" set a=Browser("Google").LookIn=dr mw.FoundFiles print i Set f=fs.com 2) Create Script to get the list of links in Google and do spell check Dim d set mw=CreateObject("Word.insert s if mw.gcreddy@gcreddy.com 117 .Create d("micclass").Spellingerrors.SearchSubFolders=True mw.page("Google").FileSearch.ReportEvent 1.FileSearch.FileSearch.count>0 then Reporter.Application") Set fs=createobject("Scripting.gcreddy.FileSearch.doc" For each dr in d msgbox dr mw.WordBasic.Application") set d=Description.Drives mw.ActiveDocument.WordBasic.childobjects(d) for i=0 to a.getROProperty("innertext") mw.quit set mw=nothing 3) Script to display all the doc files in all the drives in the system Dim mw Set mw=CreateObject("Word."Spelling"."spelling error :"&s end if mw.ActiveDocument.FileSystemObject") Set d=fs.Execute For each i in mw.GetFile(i) www.filenew s=a(i).count-1 mw.

yahoomail.com" x=Browser("CreationTime:=0").com print f.gcreddy.Navigate "www.Size&" "&f.DateCreated print "-------------------------------------------------------------------" Next Next mw.Application") ie.com 118 .Name&" "&f.GetROProperty("title") msgbox x www.Quit 5) IE Object 1) Open Internet Explorer and navigate to yahoo mail Dim ie Set ie=CreateObject("InternetExplorer.gcreddy@gcreddy.Visible=True ie.

xml) e) Library files (.xls) c) Object repository files (.gcreddy@gcreddy. Or A systematic approach to automate software Test process Why Automation Framework: In one project test automation we use various files. b) Excel files (. in order to organize and manage them all.txt). (AUT is one s/w and Testing Tool is another s/w. Work allocation and Automation Framework implementation) Etc.qrs) i) Test Result file (. Files to be used: a) Flat files (.com Automation Framework Automation: Accessing one Software Objects from another Software is called Automation. a systematic approach (Automation Framework) required. efficient and optimized way.gcreddy. we perform various tasks. Schedule.com 119 .) Automation Framework: It is a set of guidelines..vbs/.qfl) f) Test Scripts (.mts) g) Test Batch Files (..tsr) d) XML files (. www. assumptions and process developed by experts in order to perform a task(s) in an effective.XML) Tasks to be performed: a) Analyzing the application b) Selecting Areas/Test Cases for Automation c) Planning (Effort estimation.mtb) h) Recovery scenario files (.

Drawbacks: Modifications and maintenance are difficult. no concentration on Data driven testing and low performance than latest Frameworks like Keyword Driven Framework. Transaction points.reusable components can be recognized. Test Batch execution --etc) i) Defining and exporting test results j) Analyzing results k) Test reporting l) Defect Reporting using companies defect management system. Flow Control Statements. Parameterization---etc ) h) Debugging and running tests(Individual test execution. Output Values.com 120 .gcreddy. m) Modifying tests n) Performing re and regression testing ---etc Types Of Automation Framework: Automation Framework is not a qtp feature. Object repository Files.first we concentrate on creating reusable components. it’s a 3rd party concept.less command on scripts. In this Framework we create tests using recording. Record/Playback or Linear Framework (1st generation framework). Synchronization.com d) Creating Generic and project specific functions. In this Framework. Form batches and executing tests. www. Environment variable files---etc) f) Creating Tests (Using Object Repository or Descriptive Programming) g) Enhancing Tests(Inserting Checkpoints. e) Creating required Automation resources (Functions. Modular Framework. Advantages: It reduces test Automation time Performance is high than recording and playback Drawbacks: Less usage of keywords.low performance ---etc 2.(framework may vary from one company to another) 1.low resources maintenance.gcreddy@gcreddy. then creating tests using those components. And this is purely local concept.

webEdit. NOTE: Now a days Mix of Data driven and Keyword driven approaches is a famous Hybrid Framework in the industry. Any word used as the key to a code 2 A reserved word used to identify a specific command. Hybrid Framework In the above frameworks Keyword Driven framework is very famous in the industry.gcreddy@gcreddy.complex architecture.WinButton---etc) b) Functions (Built-In and User defined) c) Methods (Ex:Set.com 3.gcreddy. (in our test automation example keywords are : Keywords to be used in Test Automation: a) Test Objects (EX: Browser. function etc.page. Data Driven Framework In this Framework.we mix Data driven and Modular approaches OR Data Driven and Keyword Driven approaches---etc Advantages: Scope is very high as we mix different approaches.com 121 .We recognize positive and negative scenarios.Select. It is a mixing of more than one approach. In this approach.then collecting test data and parameterizing.Navigate---etc) d) Statements (EX:Dim.Flexible for performing any tasks. Keyword Driven Framework Keyword: 1. 4. Advantages: We can check reliability of the system.we concentrate more on Data Driven testing. Drawbacks: Less concentration on complex Functionality Testing and low keywords usage.For---etc) www. Drawbacks: Organizing and managing resources are difficult. Keyword Driven framework 5.positive and negative testing.If.Activate.low in performance.

Driver script (QTP Script file) 1) Object Repository: In this folder we store object repository files(.not---etc) Keyword Driven Approach: In this approach we use keywords for preparing tests. Object Repository 2. all team members can use this repositories. 3. but folder names may vary from one framework to another and company to another . First we create tests and make them as functions.tsr). store. Environment 3.*.gcreddy. Miscellaneous And 1. Well defined folder structure Initialization script Driver script input data spreadsheet process guidelines document Why folder structure? In order to create. 5.vbs file) 2. 2. 2) Environment: In this folder we store environment variables files(.xml). 4. www.com 122 .or. all team members can use this variables./. Initialization script (. organize and manage files a well defined folder structure required. Folder structure is a mandatory element of any framework. Test data 5. Folder Structure: 1. through framework we execute them and generate results. Key elements of Automation Framework: 1. Library a) Company b) Project Specific 4. Recovery scenarios 7.gcreddy@gcreddy.and. Test log 6.com e) Operators (EX: +.

gcreddy.com 123 . 2) Driver script (QTP Script file): It is only the qtp script. 6) Recovery scenarios: In this folder we store qtp recovery scenarios files(. we can associate all resources to this script www.vbs).qrs). another folder for storing our project specific functions(. 5) Test Log: In this folder we store test result(excel sheet).com 3) Function Library:this folder contains two sub folders one is for storing common functions of our company. 7) Miscellaneous: in this folder we store the files other than above files(ex-process guideline doc and messages among team members and instructions by team lead etc). 4) Test Data: in this folder we store test data required for data driven testing. And 1) Initialization script (.vbs file): It launches qtp tool and calls driver script.xls files or .txt files or . at end it closes qtp tool.gcreddy@gcreddy.mdb files. for that we use either .

Sign up to vote on this title
UsefulNot useful