Top Banner
1. How Does Run time data (Parameterization) is handled in QTP?A) You can then enter test data into the Data Table, an integrated spreadsheet with the full functionality of Excel, to manipulate data sets and create multiple test iterations, without programming, to expand test case coverage. Data can be typed in or imported from databases, spreadsheets, or text files. 2) What is keyword view and Expert view in QTP?A) QuickTest’s Keyword Driven approach, test automation experts have full access to the underlying test and object propertyes, via an integrated scripting and debugging environment that is round-trip synchronized with the Keyword View.Advanced testers can view and edit their tests in the Expert View, which reveals the underlying industry-standard VBScript that QuickTest Professional automatically generates. Any changes made in the Expert View are automatically synchronized with the Keyword View. 3) Explain about the Test Fusion Report of QTP ?A) Once a tester has run a test, a TestFusion report displays all aspects of the test run: a high-level results overview, an expandable Tree View of the test specifying exactly where application failures occurred, the test data used, application screen shots for every step that highlight any discrepancies, and detailed explanations of each checkpoint pass and failure. By combining TestFusion reports with QuickTest Professional, you can share reports across an entire QA and development team. 4) To which environments does QTP supports ?A) QuickTest Professional supports functional testing of all enterprise environments, including Windows, Web, ..NET, Java/J2EE, SAP, Siebel, Oracle, PeopleSoft, Visual Basic, ActiveX, mainframe terminal emulators, and Web services. 5) What is QTP ?A) QuickTest is a graphical interface record-playback automation tool. It is able to work with any web, java or windows client application. Quick Test enables you to test standard web objects and ActiveX controls. In addition to these environments, QuickTest Professional also enables you to test Java applets and applications and multimedia objects on Applications as well as standard Windows applications, Visual Basic 6 applications and .NET framework applications… 6) Explain QTP Testing process ?A) The QuickTest testing process consists of 6 main phases: 1. Create your test plan Prior to automating there should be a detailed description of the test including the exact steps to follow, data to be input, and all items to be verified by the test. The verification information should include
57
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: QTP+Questions&Answers

1. How Does Run time data (Parameterization) is handled in QTP?A) You can then enter test data into the Data Table, an integrated spreadsheet with the full functionality of Excel, to manipulate data sets and create multiple test iterations, without programming, to expand test case coverage. Data can be typed in or imported from databases, spreadsheets, or text files. 

2) What is keyword view and Expert view in QTP?A) QuickTest’s Keyword Driven approach, test automation experts have full access to the underlying test and object propertyes, via an integrated scripting and debugging environment that is round-trip synchronized with the Keyword View.Advanced testers can view and edit their tests in the Expert View, which reveals the underlying industry-standard VBScript that QuickTest Professional automatically generates. Any changes made in the Expert View are automatically synchronized with the Keyword View.

 3) Explain about the Test Fusion Report of QTP ?A) Once a tester has run a test, a TestFusion report displays all aspects of the test run: a high-level results overview, an expandable Tree View of the test specifying exactly where application failures occurred, the test data used, application screen shots for every step that highlight any discrepancies, and detailed explanations of each checkpoint pass and failure. By combining TestFusion reports with QuickTest Professional, you can share reports across an entire QA and development team. 

4) To which environments does QTP supports ?A) QuickTest Professional supports functional testing of all enterprise environments, including Windows, Web, ..NET, Java/J2EE, SAP, Siebel, Oracle, PeopleSoft, Visual Basic, ActiveX, mainframe terminal emulators, and Web services. 

5) What is QTP ?A) QuickTest is a graphical interface record-playback automation tool.   It is able to work with any web, java or windows client application. Quick Test enables you to test standard web objects and ActiveX controls. In addition to these environments, QuickTest Professional also enables you to test Java applets and applications and multimedia objects on Applications as well as standard Windows applications, Visual Basic 6 applications and .NET framework applications…

6) Explain QTP Testing process ?A) The QuickTest testing process consists of 6 main phases:

1. Create your test plan

Prior to automating there should be a detailed description of the test including the exact steps to follow, data to be input, and all items to be verified by the test.  The verification information should include both data validations and existence or state verifications of objects in the application.

1. Recording a session on your application

As you navigate through your application, QuickTest graphically displays each step you perform in the form of a collapsible icon-based test tree. A step is any user action that causes or makes a change in your site, such as clicking a link or image, or entering data in a form.

1. Enhancing your test

Page 2: QTP+Questions&Answers

o Inserting checkpoints into your test lets you search for a specific value of a page, object or text string, which helps you identify whether or not your application is functioning correctly.

NOTE:  Checkpoints can be added to a test as you record it or after the fact via the Active Screen.  It is much easier and faster to add the checkpoints during the recording process.

1.   o Broadening the scope of your test by replacing fixed values with

parameters lets you check how your application performs the same operations with multiple sets of data.

o Adding logic and conditional statements to your test enables you to add sophisticated checks to your test.

1. Debugging your test

If changes were made to the script, you need to debug it to check that it operates smoothly and without interruption.

1. Running your test on a new version of your application

You run a test to check the behavior of your application. While running, QuickTest connects to your application and performs each step in your test.

1. Analyzing the test results

You examine the test results to pinpoint defects in your application.

1. Reporting defects

As you encounter failures in the application when analyzing test results, you will create defect reports in Defect Reporting Tool.         

How QTP recognizes Objects in AUT? A) QuickTest stores the definitions for application objects in a file called the Object Repository.  As you record your test, QuickTest will add an entry for each item you interact with.  Each Object Repository entry will be identified by a logical name (determined automatically by QuickTest), and will contain a set of properties (type, name, etc) that uniquely identify each object.  Each line in the QuickTest script will contain a reference to the object that you interacted with, a call to the appropriate method (set, click, check) and any parameters for that method (such as the value for a call to the set method).  The references to objects in the script will all be identified by the logical name, rather than any physical, descriptive properties. 

9) What are the types of Object Repositorys in QTP? A) QuickTest has two types of object repositories for storing object information: shared object repositories and action object repositories. You can choose which type of object repository you want to use as the default type for new tests, and you can change the default as necessary for each new test. The object repository per-action mode is the default setting. In this mode, QuickTest automatically creates an object repository file for each action in your test so that you can create and run tests without creating,

Page 3: QTP+Questions&Answers

choosing, or modifying object repository files. However, if you do modify values in an action object repository, your changes do not have any effect on other actions. Therefore, if the same test object exists in more than one action and you modify an object’s property values in one action, you may need to make the same change in every action (and any test) containing the object.

 10) Explain the check points in QTP?A) . A checkpoint verifies that expected information is displayed in a Application while the test is running. You can add eight types of checkpoints to your test for standard web objects using QTP.

A page checkpoint checks the characteristics of a Application A text checkpoint checks that a text string is displayed in the appropriate

place on a Application. An object checkpoint (Standard) checks the values of an object on a

Application. An image checkpoint checks the values of an image on a Application. A table checkpoint checks information within a table on a Application An Accessiblity checkpoint checks the web page for Section 508 compliance. An XML checkpoint checks the contents of individual XML data files or XML

documents that are part of your Web application. A database checkpoint checks the contents of databases accessed by your

web site

11)  In how many ways we can add check points to an application using QTP.A)     We can add checkpoints while recording the application or we can add after recording is completed using Active screen (Note : To perform the second one The Active screen must be enabled while recording).

12)  How does QTP identifes the object in the applicationA)     QTP identifies the object in the application by LogicalName and Class. For example : The Edit box is identified by Logical Name : PSOPTIONS_BSE_TIME20Class: WebEdit

13)  If an application name is changes frequently i.e while recording it has name “Window1” and then while running its “Windows2” in this case how does QTP handles?A)     QTP handles those situations using “Regular Expressions”.

14)  What is Parameterizing Tests?A)     When you test your application, you may want to check how it performs the same operations with multiple sets of data. For example, suppose you want to check how your application responds to ten separate sets of data. You could record ten separate tests, each with its own set of data. Alternatively, you can create a parameterized test that runs ten times: each time the test runs, it uses a different set of data.

15)  What is test object model in QTP ? A) The test object model is a large set of object types or classes that QuickTest uses to represent the objects in your application. Each test object class has a list of properties that can uniquely identify objects of that class and a set ofrelevant methods that QuickTest can record for it.A test object is an object that QuickTest creates in the test or component to represent the actual object in your application. QuickTest stores information about the object that will help it identify and check the object during the run session.A run-time object is the actual object in your Web site or application onwhich methods are performed during the run session.When you perform an operation on your application while recording,QuickTest:➤ identifies the QuickTest test object class that represents the

Page 4: QTP+Questions&Answers

object on whichyou performed the operation and creates the appropriate test object➤ reads the current value of the object’s properties in your application andstores the list of properties and values with the test object➤ chooses a unique name for the object, generally using the value of one of itsprominent properties➤ records the operation that you performed on the object using the appropriate QuickTest test object methodFor example, suppose you click on a Find button with the following HTMLsource code:<INPUT TYPE=”submit” NAME=”Find” VALUE=”Find”>QuickTest identifies the object that you clicked as a WebButton test object.It creates a WebButton object with the name Find, and records the followingproperties and values for the Find WebButton:It also records that you performed a Click method on the WebButton.QuickTest displays your step in the Keyword View like this:QuickTest displays your step in the Expert View like this:Browser(”Mercury Interactive”).Page(”Mercury Interactive”).WebButton(”Find”).Click 

16)  What is Object Spy in QTP?A) Using the Object Spy, you can view the properties of any object in an openapplication. You use the Object Spy pointer to point to an object. The ObjectSpy displays the selected object’s hierarchy tree and its properties and valuesin the Properties tab of the Object Spy dialog box. 

17.       Supported Check-Points in QTP?17)      What is the Diff between Image check-point and Bit map Check point?A) Image checkpoints enable you to check the properties of a Web image. You can check an area of a Web page or application as a bitmap. While creating a test or component, you specify the area you want to check by selecting an object. You can check an entire object or any area within an object. QuickTest captures the specified object as a bitmap, and inserts a checkpoint in the test or component. You can also choose to save only the selected area of the object with your test or component in order to save disk Space For example, suppose you have a Web site that can display a map of a city the user specifies. The map has control keys for zooming. You can record the new map that is displayed after one click on the control key that zooms inthe map. Using the bitmap checkpoint, you can check that the map zooms in correctly.You can create bitmap checkpoints for all supported testing environments(as long as the appropriate add-ins are loaded).Note: The results of bitmap checkpoints may be affected by factors such asoperating system, screen resolution, and color settings. 

1       How many ways we can parameterize data in QTP ?A) There are four types of parameters:Test, action or component parameters enable you to use values passedfrom your test or component, or values from other actions in your test. Data Table parameters enable you to create a data-driven test (or action)that runs several times using the data you supply. In each repetition, oriteration, QuickTest uses a different value from the Data Table. Environment variable parameters enable you to use variable values fromother sources during the run session. These may be values you supply, orvalues that QuickTest generates for you based on conditions and optionsyou choose. Random number parameters enable you to insert random numbers asvalues in your test or component. For example, to check how yourapplication handles small and large ticket orders, you can have QuickTestgenerate a random number and insert it in a number of tickets edit field. 

20. How do u do batch testing in WR & is it possible to do in QTP, if so explain?     Ans: Batch Testing in WR is nothing but running the whole test set by selecting “Run Testset” from the “Execution Grid”.The same is possible with QTP also. If our test cases are automated then by selecting “Run Testset” all the test

Page 5: QTP+Questions&Answers

scripts can be executed. In this process the Scripts get executed one by one by keeping all the remaining scripts in “Waiting” mode. 

21. if i give some thousand tests to execute in 2 days what do u do?               Ans : Adhoc testing is done. It Covers the least basic functionalities to verify that the system is working fine. 

22. what does it mean when a check point is in red color? what do u do?       Ans : A red color indicates  failure. Here we analyze the the cause for failure whether it is a  Script Issue or Envronment Issue or a Application issue.  

23. what do you call the window testdirector-testlab?      Ans : “Execution Grid”. It is place from where we Run all Manual / Automated Scripts 

24. how do u create new test sets in TD     Ans : Login to TD.          Click on “Test Lab” tab.          Select the Desired folder under which we need to Create the Test Set. ( Test Sets can be grouped as per module.)          Click on “New Test Set or Ctrl+N” Icon to create a Test Set.  

25. How do u do batch testing in WR & is it possible to do in QTP, if so explain?            Ans : You can use Test Batch Runner to run several tests in succession. The results for each test are stored in their default location.  Using Test Batch Runner, you can set up a list of tests and save the list as an .mtb file, so that you can easily run the same batch of tests again, at another time. You can also choose to include or exclude a test in your batch list from running during a batch run  

26. if i give some thousand tests to execute in 2 days what do u do?           Ans : Adhoc testing is done. It Covers the least basic functionalities to verify that the system is working fine. 

27. what does it mean when a check point is in red color? what do u do?       Ans : A red color indicates  failure. Here we analyze the the cause for failure whether it is a Script Issue or Envronment Issue or a Application issue. 

28. what do you call the window testdirector-testlab?      Ans : “Execution Grid”. It is place from where we Run all Manual / Automated Scripts 

29. how do u create new test sets in TD     Ans : Login to TD.          Click on “Test Lab” tab.          Select the Desired folder under which we need to Create the Test Set. ( Test Sets can be grouped as per module.)          Click on “New Test Set or Ctrl+N” Icon to create a Test Set.    

 30. How to Import data from a “.xls” file to Data table during Runtime.           Ans :   Datatable.Import “…XLS file name…”                   DataTable.ImportSheet(FileName, SheetSource, SheetDest)                   DataTable.ImportSheet “C:\name.xls” ,1 ,”name”   

31. How to export data present in Datatable to an “.xls” file?           Ans :  DataTable.Export  “….xls file name…”   

32. How to get Traceability matrix from TD? 33. How to import a test case present in “.xls” file to TD under a Test set? 

Page 6: QTP+Questions&Answers

34. How to attach a file to TD? 35. What do you to script when objects are removed from application? 36. Syntact for how to call one script from another? and Syntax to call one “Action” in another?    Ans:   RunAction ActionName, [IterationMode , IterationRange , Parameters]      Here the actions becomes reusable on making this call to any Action.     IterationRange  String  Not always required. Indicates the rows for which action iterations will be performed. Valid only when the IterationMode is rngIterations. Enter the row range   (i.e. “1-7″), or enter rngAll to run iterations on all rows.     If the action called by the RunAction statement includes an ExitAction statement, the RunAction statement can return the value of the ExitAction’s RetVal argument.  

 37. How to export QTP results to an “.xls” file?      Ans : (a) By default it creates an “XML” file and displays the results  

38. 3 differences between QTP & Winrunner?      Ans :            (a) QTP is object bases Scripting ( VBS) where Winrunner is TSL (C based) Scripting.              (b) QTP supports “.NET” application Automation not available in Winrunner            (c) QTP has “Active Screen” support which captures the application, not available in WR.              (d) QTP has “Data Table” to store script values , variables which WR does not have.            (e) Using a  “point and click” capability you can easily interface with objects, their definitions and create checkpoints after having recorded a script – without having to navigate back to that location in your application like you have to with WinRunner. This greatly speeds up script development.            

 39. How to create a Runtime property for an object?  

40. how to add a runtime parameter to a datasheet?      Ans: DataTable.LocalSheet                  The following example uses the LocalSheet property to return the local sheet of the run-time Data Table in order to add a parameter (column) to it.                  MyParam=DataTable.LocalSheet.AddParameter(”Time”, “5:45″)   

41. What scripting language is QTP of?        Ans : Vbs 

42. Analyzing the Checpoint results    Standard Checpoint :By adding standard checkpoints to your tests or components, you can compare the expected values of object properties to the object’s current  values during a run session. If the results do not match, the checkpoint                        fails.   

43.Table and DB Checkpoints:           By adding table checkpoints to your tests or components, you can check that a specified value is displayed in a cell in a table on your application. By adding database checkpoints to your tests or components, you can check the contents of databases accessed by your application.            The results displayed for table and database checkpoints are similar. When you run your test or component, QuickTest compares the expected results of the checkpoint to the actual results of the run session. If the results do not match, the checkpoint fails.            You can check that a specified value is displayed in a cell in a table by adding a table checkpoint to your test or component. For ActiveX tables, you can also check the properties of the table object. To add a table checkpoint, you use the Checkpoint Properties dialog box.            Table checkpoints are supported for Web and ActiveX applications, as well as for a variety of external add-in environments.            You can use database checkpoints in your test or component to check databases accessed by your Web site or application and to detect defects. You define a query on your database, and then you create a database checkpoint that checks the results of the

Page 7: QTP+Questions&Answers

query.            Database checkpoints are supported for all environments supported by QuickTest, by default, as well as for a variety of external add-in environments.            There are two ways to define a database query:            (a) Use Microsoft Query. You can install Microsoft Query from the custom installation of Microsoft Office.           (b) Manually define an SQL statement.          The Checkpoint timeout option is available only when creating a table checkpoint. It is not              available when creating a database checkpoint  

44.Checking Bitmaps:            You can check an area of a Web page or application as a bitmap. While creating a test or component, you specify the area you want to check by selecting an object. You can check an entire object or any area within an object. QuickTest captures the specified object as a bitmap, and inserts a checkpoint in the test or component. You can also choose to save only the selected area of the object with your test or component in order to save disk space.            When you run the test or component, QuickTest compares the object or selected area of the object currently displayed on the Web page or application with the bitmap stored when the test or component was recorded. If there are differences, QuickTest captures a bitmap of the actual object and displays it with the expected bitmap in the details portion of the Test Results window. By comparing the two bitmaps (expected and actual), you can identify the nature of the discrepancy. For more information on test results of a checkpoint, see Viewing Checkpoint Results.            For example, suppose you have a Web site that can display a map of a city the user specifies. The map has control keys for zooming. You can record the new map that is displayed after one click on the control key that zooms in the map. Using the bitmap checkpoint, you can check that the map zooms in correctly.            You can create bitmap checkpoints for all supported testing environments (as long as the appropriate add-ins are loaded). Note: The results of bitmap checkpoints may be affected by factors such as operating system, screen resolution, and color settings. 

 45.Text/Text Area Checkpoint :           In the Text/Text Area Checkpoint Properties dialog box, you can specify the text to be checked as well as which text is displayed before and after the checked text. These configuration options are particularly helpful when the text string you want to check appears several times or when it could change in a predictable way during run sessions.            Note: In Windows-based environments, if there is more than one line of text selected, the Checkpoint Summary pane displays [complex value] instead of the selected text string. You can then click Configure to view and manipulate the actual selected text for the checkpoint.            QuickTest automatically displays the Checked Text in red and the text before and after the Checked Text in blue. For text area checkpoints, only the text string captured from the defined area is displayed (Text Before and Text After are not displayed).            To designate parts of the captured string as Checked Text and other parts as Text Before and Text After, click the Configure button. The Configure Text Selection dialog box opens Checking XML :           XML (Extensible Markup Language) is a meta-markup language for text documents that is endorsed as a standard by the W3C. XML makes the complex data structures portable between different computer environments/operating systems and programming languages, facilitating the sharing of data.            XML files contain text with simple tags that describe the data within an XML document. These tags describe the data content, but not the presentation of the data. Applications that display an XML document or file use either Cascading Style Sheets (CSS) or XSL Formatting Objects (XSL-FO) to present the data.                     You can verify the data content of XML files by inserting XML checkpoints. A few common uses of XML checkpoints are described below:            An XML file can be a static data file that is accessed in order to retrieve commonly used data for which a quick response time is needed—for example, country names, zip codes, or area codes. Although this data can change over time, it

Page 8: QTP+Questions&Answers

is normally quite static. You can use an XML file checkpoint to validate that the data has not changed from one application release to another.          An XML file can consist of elements with attributes and values (character data). There is a parent and child relationship between the elements, and elements can have attributes associated with them. If any part of this structure (including data) changes, your application’s ability to process the XML file may be affected. Using an XML checkpoint, you can check the content of an element to make sure that its tags, attributes, and values have not changed.          XML files are often an intermediary that retrieves dynamically changing data from one system. The data is then accessed by another system using Document Type Definitions (DTD), enabling the accessing system to read and display the information in the file. You can use an XML checkpoint and parameterize the captured data values in order to check an XML document or file whose data changes in a predictable way.          XML documents and files often need a well-defined structure in order to be portable across platforms and development systems. One way to accomplish this is by developing an XML schema, which describes the structure of the XML elements and data types. You can use schema validation to check that each item of content in an XML file adheres to the schema description of the element in which the content is to be placed.  

46 . Object Repositories types, Which & when to use?           Deciding Which Object Repository Mode to Choose            To choose the default object repository mode and the appropriate object repository mode for each test, you need to understand the differences between the two modes.            In general, the object repository per-action mode is easiest to use when you are creating simple record and run tests, especially under the following conditions:            You have only one, or very few, tests that correspond to a given application, interface, or set of objects.          You do not expect to frequently modify test object properties.          You generally create single-action tests.          Conversely, the shared object repository mode is generally the preferred mode when:            You have several tests that test elements of the same application, interface, or set of objects.          You expect the object properties in your application to change from time to time and/or you regularly need to update or modify test object properties.          You often work with multi-action tests and regularly use the Insert Copy of Action and Insert Call to Action options. 

47. Can we Script any test case with out having Object repository? or Using Object Repository is a must?           Ans: No. U can script with out Object repository by knowing the Window Handlers, spying and recognizing the               objects logical names and properties available.  

48. How to execute a WinRunner Script in QTP?           Ans : (a) TSLTest.RunTest TestPath, TestSet [, Parameters ] –> Used in QTP 6.0 used for backward compatibility                    Parameters : The test set within Quality Center, in which test runs are stored. Note that this argument is relevant only when working with a test in a Quality Center project. When the test is not saved in Quality Center, this parameter is ignored.                e.g : TSLTest.RunTest “D:\test1″, “”         (b) TSLTest.RunTestEx TestPath, RunMinimized, CloseApp [, Parameters ]                     TSLTest.RunTestEx “C:\WinRunner\Tests\basic_flight”, TRUE, FALSE, “MyValue” CloseApp : Indicates whether to close the WinRunner application when the WinRunner test run ends.           Parameters : Up to 15 WinRunner function argument          

 49. How to handle Run-time errors?           (a) On Error Resume Next : causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most

Page 9: QTP+Questions&Answers

recent call out of the procedure containing the On Error Resume Next statement. This allows execution to continue despite a run-time error. You can then build the error-handling routine inline within the procedure.          Using “Err” object msgbox  “Error no: ” & “  ” & Err.Number & “      ” & Err.description & “  ” & Err.Source & Err.HelpContext 

 50. How to change the run-time value of a property for an object?           Ans : SetTOProperty changes the property values used to identify an object during the test run.                   Only properties that are included in the test object description can be set  

51. How to retrieve the property of an object?           Ans :  using “GetRoProperty”.  

52. How to open any application during Scripting?           Ans : SystemUtil , object used to open and close applications and processes during a run session.           (a) A SystemUtil.Run statement is automatically added to your test when you run an application from the Start menu or the Run dialog box while recording a test          E.g :        SystemUtil.Run “Notepad.exe”                             SystemUtil.CloseDescendentProcesses ( Closes all the processes opened by QTP ) 

53. Types of properties that Quick Test learns while recording?           Ans : (a) Mandatory (b) Assistive .                      In addition to recording the mandatory and assistive properties specified in the Object Identification dialog box, QuickTest can also record a backup ordinal identifier for each test object. The ordinal identifier assigns the object a numerical value that indicates its order relative to other objects with an otherwise identical description (objects that have the same values for all properties specified in the mandatory and assistive property lists). This ordered value enables QuickTest to create a unique description when the mandatory and assistive properties are not sufficient to do so.  

 54. What is the extension of script and object repository files?           Ans :  Object Repository : .tsr   ,  Script :  .mts, Excel : Default.xls 

55. How to supress warnings from the “Test results page”?                    Ans : From the Test results Viewer “Tools > Filters > Warnings”…must be “Unchecked”. 55. When we try to use test run option “Run from Step”, the browser is not launching automatically why?           Ans : This is default behaviour.

 56. Does QTP is “Unicode” compatible?                    Ans : QTP 6.5 is not but QTP 8.0 is expected to be Unicode compatabile by end of December 2004. 

57. How to “Turn Off” QTP results after running a Script?           Ans : Goto “Tools > Options > Run Tab” and Deselect “View results when run session ends”. But this supresses only the result window, but a og will be created and can viewed manulaly which cannot be restricted from getting created. 

58. How to get “FontSize” of a “WebEdit”? 

59. Is there anyway to automatically update the Datasource name in Database Checkpoints object when we  migrate tests to a new release? 

Page 10: QTP+Questions&Answers

60. How to verify the Cursor focus of a certain field?           Ans : Use “focus” property of “GetRoProperty” method” 6

1. Any limitation to XML Checkpoints?           Ans : Mercury has determined that 1.4MB is the maximum size of a XML file that QTP 6.5 can handle 

62. How to make arguments optional in a function?                    Ans : this is not possible as default VBS doesn’t support this. Instead you can pass a blank scring and have a default value if arguments r not required. 

63. How to covert a String to an integer?                    Ans : CInt()—> a conversion function available.

 64. Inserting a Call to Action is not Importing all columns in Datatable of globalsheet. Why?           Ans : Inserting a call to action will only Import the columns of the Action called       

Automated Test Script Creation Process 

Debugging and troubleshooting test scripts becomes extremely tedious when the test script has hundreds of lines of code, verification points, branching logic, error handling, parameters, and test correlation among various recorded business processes.  A more manageable approach to debugging complex and lengthy test scripts is to record portions of the script and debug those portions individually before recording other parts of the test script.  After testing individual portions, you can determine how one portion of the test script works with another portion and how data flows from one recorded process to the other.  After all sections for a test script have been recorded, you can playback the entire test script and ensure that it properly plays back from the beginning to the end with one or more sets of data.  Always create a test plan that will assist in the creation of the regression test script.  A test script is only as good as the planning that takes place before it is written.  This saves time and organizes the process.  Remember that all regression test scripts will be written to run in the QA environment as well as the production environment.  The automated regression test use will be a part of the production test used to determine if a build truly does function as expected in production.To manage the creation and edit of our automated regression tests QA will create automated tests in the following manner:

1.                  Record each individual process such as logging in and logging out. Save those recordings on your desktop.

2.                  Verify that the script will play back with no errors.3.                  Continue recording and playing back throughout the test script creation

process, verifying the script will play back with each step taken.4.                  Add multiple sets of data driven tests for each individual portion of each test

where that kind of test is applicable.5.                  Verify the individual test scripts with multiple sets of data will play back

with no errors.6.                  Add various check points throughout the test. 

Page 11: QTP+Questions&Answers

7.                  Verify the individual test scripts with various check points will play back with no errors.

8.                  Now integrate all recorded processes into one large test script.  9.                  Verify the large test script will play back with no errors.

The key here is to ensure that each recorded process plays back successfully before proceeding to record the remaining portions of the entire test script.  Do not string the individual tests together for playback without first verifying that all of the processes could play back successfully as individual processes.Lesson to be learned here is to never, EVER wait to debug a script until the entire test script has been recorded.SynchronizationSince QTP can play back recorded test scripts much faster than an end-user’s manual keystrokes all tests must be synchronized.  Introduce artificial wait times in the test scripts to make sure the script will run appropriately without errors unattended.  Take into account the fact that there will be times when the script will need to run slower than a manual test due to network issues, etc.  The goal here is we want to make sure the scripts will run unattended through Test Director.  Slowing down a script with wait times is not very scientific and does not contribute to the creation of a robust automated test script that plays back successfully without user intervention.  That said, sync times will be edited after the test script has been written in its entirety and has been tested to ensure it runs with no errors.Signed-off, Peer ReviewedAs part of the test readiness review criteria, test scripts will be formally accepted and approved prior to starting the test cycle.  QA, Business Analysts and Developers should be involved in approving recorded test scripts.  The QA Analyst writing the automated test script should demonstrate that the test script successfully plays back in the QA environment and, if possible, with various sets of data.Recording, Playing Back Against Hidden ObjectsScripts might be recorded to populate or double click values for a field within a table grid or an array where the location of this field is not fixed.  If the field’s location within a table grid or array changes from the time it was recorded, the script might fail during play back.  Test scripts often fail during play back because the locations of objects that are not displayed or visible within the screen have changed.In order to play back scripts that are location sensitive or where the location is subject to change, it might be necessary to enhance the script with functionality such as ‘scroll down’, ‘next page’, or ‘find’.  Including such utilities ensures that hidden objects requiring play back will be identified, and/or double clicked regardless of their location within an array, table grid, or the displayed screen.Create Automatic Notification for Critical ScriptsTest scripts should be enhanced with error handling programming logic that instantly sends error messages to a tester’s e-mail address when problems occur.  Since some test scripts are business critical and must run as batch jobs in the middle of the night we need to know if something failed as soon as possible.  The proper and successful execution of these business critical test scripts can serve as a dependency or pre-condition for other automated tasks.  Always include logic in business critical test scripts that automatically sends notification in the event of a failure.

Page 12: QTP+Questions&Answers

DocumentationTo make test scripts reusable and easier to maintain, please document all relevant information for executing the test script, a test script header, and any special conditions for execution of the test script.  Example:

1.                  Adjust dates within the application in QA environment for running reports.2.                  Update any fields that require unique data.3.                  Display settings for context sensitive/analog/bitmap recording.4.                  List other test scripts that are dependencies.5.                  Specify necessary authorization levels or user roles for executing the script.6.                  Conditions under which the script can fail and work around for re-launching

the script.7.                  Applications that need to be either opened or closed during the script

execution.8.                  Specific data formats, etc.

Scripts should contain a header with a description (example: what it is used for) and its particular purpose (example: regression testing).  The script header should also include the script author and owner, creation and modification date, requirement identifiers that the script traces back to, the product the script supports and the number of variables and parameters of the script.  Providing this information in the test script header facilitates the execution, modification, and maintenance of the script for future testing efforts.

How to Close QTP after execution 

Private Function CloseQTP            Set objWMIService = GetObject(”winmgmts:\\.\root\CIMV2″)            Set colProcess = objWMIService.ExecQuery (”Select * from Win32_Process Where Name = ‘QTPro.exe’”)            For Each objProcess in colProcess                        objProcess.Terminate()            Next            Set objWMIService = Nothing            Set colProcess = NothingEnd FunctionCall CloseQTP

What is the QuickTest Automation Object Model?

You can use the QuickTest Professional Automation Object Model to write programs that automate your QuickTest operations. The QuickTest Automation Object Model provides objects, methods, and properties that enable you to control QuickTest from another application. The new QuickTest Professional Automation Object Model enables you to automate test management. You can now control virtually every QuickTest feature and capability using the objects, methods and properties included in the QuickTest Professional Automation Object Model. Automation scripts make it easy to perform any QuickTest operation multiple times in multiple tests without having to open the QuickTest application, for example,

You can write a script that modifies the test object description properties in the Object Identification dialog box and performs an update run on all tests in a specified file folder.

Page 13: QTP+Questions&Answers

After installing a new add-in, an automation script can associate this add-in to all relevant tests.

You can write an automation script to run a selected batch of tests. For each test, you can retrieve the associated add-ins list. Then, if the necessary add-ins are not already loaded, you can close QuickTest, load the necessary add-ins, reopen QuickTest, and run the test.

You can define your settings for a test in QuickTest, then click “Generate Script” in the Generate tab of the Test Settings dialog box to generate an automation script based on the current test settings. You can then apply those same settings automatically to multiple tests using the whole automation script or excerpts from the generated file.

Example:You can create and run an automation program from Microsoft Visual Basic that loads the required add-ins for a test, starts QuickTest in visible or minimized mode, opens the test, configures settings that correspond to those in the Options, Test Settings, and Record and Run Settings dialog boxes, runs the test, and saves the test. Creating automation programs:The Properties tab of the Test Settings dialog box, the General tab of the Options dialog box, and the Object Identification dialog box each contain a “Generate Script” button. Clicking this button generates a automation script file (.vbs) containing the current settings from the corresponding dialog box. You can run the generated script as is to open QuickTest with the exact configuration of the QuickTest application that generated the script, or you can copy and paste selected lines from the generated files into your own automation script. Generating an automation script for QuickTest Professional options:1. Go to Tools -> Options.2. Select the General tab.3. Click <Generate Script>.4. Save the script to the desired location.5. Click <OK> to close the Options dialog. Generating an automation script for test settings:1. Go to Test -> Settings.2. Select the Properties tab.3. Click <Generate Script>.4. Save the script to the desired location.5. Click <OK> to close the Test Settings dialog. Generating an automation script for object identification settings:1. Go to Tools -> Object Identification.2. Click <Generate Script>.3. Save the script to the desired location.4. Click <OK> to close the Object Identification dialog. The QuickTest Automation Object Model Reference file is a help file that provides detailed descriptions, syntax information, and examples for the objects, methods, and properties in the QuickTest Automation Object Model.

Page 14: QTP+Questions&Answers

When QuickTest Professional 6.5 is installed you can open the QuickTest Automation Object Model Reference from:

The QuickTest program folder (Start -> Programs -> QuickTest Professional -> Documentation -> Automation Object Model Reference)

The QuickTest Help menu (Help -> QuickTest Automation Object Model Reference)

Get the name of the open browser::

Set browserDesc = Description.Create()

browserDesc(”application version”).Value = “internet explorer 6″

Set browserColl = DeskTop.ChildObjects(browserDesc)

browserCnt = browserColl.Count

MsgBox “There are “&browserCnt&” instances of a browser”

 For i = 0 To (browserCnt -1)

MsgBox “Browser # “&i&” has title = “& browserColl(i).GetROProperty(”title”)

Next ‘ i

 Set browserColl = Nothing

Set browserDesc = Nothing

General Standards to be followed in Test scripts

Indent the code to make it readable and understandable for others.

Avoid hard coding system specific values like folder locations, instead set it relatively with respect to the Main/Startup script.

Use synchronization functions instead of wait () function. Use GUI checkpoints for all static links, buttons and edit fields in

every page (optional) Use parameterization instead of using hard coded data to

populate the AUT. All references returned by the AUT must be written to the data

table and verified later. These references must be written to the test report as well.

All automation steps should be properly commented.

Page 15: QTP+Questions&Answers

All Logic should be commented and explained. The Global data sheet should not be used for importing any test

data. The Global sheet should be used only when there are any

parameters to be passed in between actions or when certain data has to be maintained through out the test.

Use the local sheet to import any test data. All actions except the main calling action are to be reusable

action. Declare all variables used in the action in the start of the action

itself. While using condition statements to control flow, indent the line, for easy readability.

Test Script Format

 The test scripts are developed using Quick Test Pro tool. The initial action of each subgroup starts the XYZ application and executes the test conditions. Each script executes the test conditions. The expected result is verified with the actual outcome whenever required.  Given below is a sample test script format to be kept in the start of each action

‘******************************************************************************************************************‘

Script Name                             :        ABC_TC01‘

Author                                      :        

 ‘Created On                               :      

  ‘Referred Test Case Number        :        XYZ_TC_01‘Target Application                     :        XYZ Application‘Purpose / Description                :        To validate the XYZ application ABC functionality‘Data Sheet Name                       :        Global Sheet‘TSR Path                                   :        

 ‘Revision Date                           :        NIL‘Revised By                      :        NIL‘Changes                                    :        NIL ‘*************************************************************************************************************Option Explicit ‘This will FORCE the user to declare the variables Note:XYZ – Application nameABC – Module nameTC – Test Case    

Step Results

Page 16: QTP+Questions&Answers

 Pass Step Result: Reporter.ReportEvent 0,”Step-1”, “Message: Logged in Successfully”                                       Or Reporter.ReportEvent micPass,”Step-1”, “Message: Logged in Successfully”  Fail Step Result: Reporter.ReportEvent 1,”Step-ER-1”, “Error Message: Log in Failed”                                       Or Reporter.ReportEvent micFail,”Step-ER-1”, “Error Message: Log in Failed”   

Maintenance Run Mode :

Repair your test on the fly, this will assists you to  adding the steps or uodating the object proprties in OR on the fly.i.e. if your object properties are changed after a new build, you just run the Maintenance Run Mode and update your OR according to that on the fly.

Process Guidance :

This is little more than more accessible help files. Maybe this is good for when you are first learning to record a test, but it doesn’t seem to add much utility.

Flow Pane

Available Keywords Pane

All Test Objects and functions in one handy location.Rapid test development with drag & drop.Object repository now also supports drag & drop

Page 17: QTP+Questions&Answers

Resources Pane :

All resources associated with the test. You can see all your library file in this pane

Page 18: QTP+Questions&Answers

Missing Resources Pane Relative Path Helper Improved Bitmap Checkpoint Web Extensibility :

1.Anyone can add support for new web controls

2.Rapid development in JavaScript

3.Solid infrastructure supplied by the Web add-in

4.Extensibility objects are first class citizens

 5.Built-in toolkit: ASPAjax

Tabbed browsing :

Tabs identified as separate browsers.Same test compatible with tabbed and non tabbed browsers.

New Technologies :

1.PowerBuilder

Page 19: QTP+Questions&Answers

2. Oracle − Forms 10 −Apps 12

3.StingRay Objective Grid 10, 114. PeopleSoft 9.0•

4.New Terminal Emulator versions

5.NET 3.5 (beta)

New environments  :

1.Windows Vista 64 bit

2. Eclipse 3.2, 3.3

3.Record on SWT

4. Firefox 3.0

5.Netscape 9

Reference: HP website

You can download QTP 9.5 on HP website https://h10078.www1.hp.com/cda/hpms/display/main/hpms_content.jsp?zn=bto&cp=1-11-127-24^1352_4000_100__

1) How to Stop  the execution of the test.

    Syntax

   Services.Abort 2)How to add folders

Sub AddNewFolder(path, folderName)    Dim fso, f, fc, nf     Set fso = CreateObject(”Scripting.FileSystemObject”)     Set f = fso.GetFolder(path)

    Set fc = f.SubFolders     If folderName <> “” Then

      Set nf = fc.Add(folderName)

   Else       Set nf = fc.Add(“New Folder”)

Page 20: QTP+Questions&Answers

    End If End Sub

An error occurs if the folderName already exists.

3 )How to get the ASCII valuse for a character

Remarks

In the following example, Asc returns the ANSI character code of the first letter of each string:

Dim MyNumber MyNumber = Asc(“A”)    

   ‘ Returns 65.

 MyNumber = Asc(“a”)

       ‘ Returns 97.

 MyNumber = Asc(“Apple”)   ‘ Returns 65.

Note   The AscB function is used with byte data contained in a string. Instead of returning the character code for the first character, AscB returns the first byte. AscW is provided for 32-bit platforms that use Unicode characters. It returns the Unicode (wide) character code, thereby avoiding the conversion from Unicode to ANSI.

4) How to get Character fron ASCII value

Remarks

Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character.

The following example uses the Chr function to return the character associated with the specified character code:

Dim MyChar MyChar = Chr(65)   ‘ Returns A. MyChar = Chr(97)   ‘ Returns a.MyChar = Chr(62)   ‘ Returns >. MyChar = Chr(37)   ‘ Returns %.

Note   The ChrB function is used with byte data contained in a string. Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte. ChrW is provided for 32-bit platforms that use Unicode characters. Its argument is a Unicode (wide) character code, thereby avoiding the conversion from ANSI to Unicode.

Page 21: QTP+Questions&Answers

5)Accessing User-Defined Properties of Web Objects

You can use the attribute/<property name> notation to access native properties of Web objects and use these properties to identify such objects with programmatic descriptions. For example, suppose a Web page has the same company logo image in two places on the page: <IMG src=”logo.gif” mce_src=”logo.gif” LogoID=”122″> <IMG src=”logo.gif” mce_src=”logo.gif” LogoID=”123″> You could identify the image that you want to click using a programmatic description by including the user-defined property LogoID in the description as follows: Browser(”Mercury Tours”).Page(”Find Flights”).Image(”src:=logo.gif”,”attribute/LogoID:=123″).Click 68, 12 Note: The attribute/<property name> notation is not supported in Netscape 4.x.

6)How to Run Your Automation Program

There are several applications available for running automation programs. You can also run automation programs from command line using Microsoft’s Windows Script Host. For example, you could use the following command line to run your automation program: WScript.exe /E:VBSCRIPT myScript.vbs 7) What is the other way of making coments instead of astrik(‘)

Ans: “Hello” : Rem Comment after a statement separated by a colon.

8)How to run commands in command prompt from qtpAns:You can run standard DOS commands in your QuickTest test using the VBScript Windows Scripting Host Shell object (WSCript.shell). For example, you can open a DOS command window, change the path to C:\, and execute the DIR command using the following statements: Dim oShell Set oShell = CreateObject (”WSCript.shell”) oShell.run “cmd /K CD C:\ & Dir” Set oShell = Nothing 9) what is optional stepAns:

Description

Causes a step to be bypassed if an object in that step is not found.

Syntax

OptionalStep.StatementToMakeOptional

Example

The following example uses the OptionalStep object to make the Paris selection from the Depart WebList an optional step. OptionalStep.Browser(”Mercury Tours”).Page(”Find Flights”).WebList(”depart”).Select “Paris” 10)What is the alternative way to getROpropertyAns) object.QueryValue(property to get)11)How to get the number of childs in a tree a) Object.children.lengthex: Browser(”xxx”).Page(”xxx”).Image(”xxx”).Object.children.length11)How to know

Page 22: QTP+Questions&Answers

that the table has no recordsa) rs.RecordCount 12)What are the types of parameters available in QTPa) 3 types   1)  Action Parameters(Input ,output)These parameters are restricted to that action only.i.e we can not use them for another action.Note:Don’t think that the output action parameter can pass values between action.The only purpouse with output action parameter is to assign the values at run time rather than design time from the external source(application)Advantage: These parameters are bound to the action even this action is called from another test.How to Declare: Using Action property tabSyntax: Input parameter —variable= parameter(“name”)              Output parameter—Parameter(“name”)=value              2)  Test Parameters(Input ,output)These parameters are not restricted to that action i.e we can use them for any nother action.Note These parameters are not found and unable to use them in any action  is called from another test.Advantage: test  parameters can pass values between action.How to Declare: Using  Test Setting- parameters tabSyntax: Input parameters—   variable= TestArgs (“name”)Output parameters–   TestArgs (“name”)=value3)Local ParametersThese are also same as test parameters but we need to Declare and use them from code not from IDE.Advantage:These parameters still can used even the actions are called from any testSyntax:Declaration LocalParameter(“name”)=valueUse: variable= LocalParameter(“name”)13)what are the different ways to delay the execution steps in QTPAns)3 ways1) object.waitProperty ”propertyName”,”value”,”time in milli sec”This is called conditional wait  This will pauses the execution as long as the specified value of the property exist in the AUT or specified time out which ever is earlier2) Wait(seconds)This is called unconditional wait.i.e it will wait for the specified time3) Services.ThinkTime 10Same as wait14) How to minimize QTP while runninga) Set qtApp = CreateObject(”QuickTest.Application”)    qtApp.WindowState = “Minimized”     Set qtApp = Nothing

QTP Naming Convention 

Notation to Be Used For Automation Objects

 Checkbox = chk                                                      Dialog Box = dbDisplay = displ                                                         Icon = icLabel = lbl                                                              Links = linkList Box = lb                                                           List View = lvLogo = logo                                                            Menu = mMenu Item = mi                                                       Message Box = mbPopup List = poplst                                                  Push Button = pbRadio Button = rb                                                    Scroll Bar = sbStatic Text = stxt                                                    Status Bar = stbrTab = tab                                                               Table = tblText Box = txt                                                         Tool Bar = tbTree View = tv                                                       Header = hdrPanel = pan                                                             Status Window =

Page 23: QTP+Questions&Answers

stwinSplitter = sp                                                            Container = ctnNavigation bar = nb                                                 Grid = grdCombo box = cbx                                                    Window = win         

Test Scripts

 The test scripts name

Must consist of alphabets, numbers and ‘_’. Must start with an upper case letter. If more than one word is used, the starting of every word must

be in Upper case.      (Eg: Test_Script) Name of the script must be in the format – Application/Test

group, Feature/Action Number (XYZ_01).

 

VBS Files A  VBScript file name must consist of alphabets. Name should preferably be in the format

Project_Module_Function

 

Functions Must consist of alphabets. Must start with ‘func’. Name must stand for the functionality of the function. If more than one word is used, the starting of every word should

be in capitals. Numerical are not allowed in the names

          Eg:  Public function funcOpenWindow (in window_name) 

 Constants and Variables Name of a constant must be in upper case letters with

underscores in it.  Eg: public const OR_PATH_DIR= c:\\mytests\\Action1; 

Name of a variable must be of lowercase letters and can contain underscores and digits. Eg: public my_variable_name=”This is my variable”;

        Declare all the variables using DIM.

Page 24: QTP+Questions&Answers

Object Repository Object repository file name must consist of alphabets and should

be like project_Module_Function.tsr. If the name of an object or window is ambiguous, then it must be

renamed in the format ObjectType_Label. Eg: Button_Done, Window_EngagementSummry, Checkbox_Overage, Radio_Awarded etc.

If more than one word is used, the starting of every word should be in capitals.

 

Recovery Manager Name of a Recovery Manager file must be of alphabets and if

necessary digits. The files must be of the format Project_Module_Function_in.qrs.

How To close MsgBox Runtime 

Write the below line as the first-line in your script. Set sh = CreateObject(”Scripting.Shell”) …This will create a shell object at run-time and will be available until the test ends.

If you are getting problem like ,Activex Component can’t create object Then use  Set sh =CreateObject(”WScript.Shell”)

 Now… where ever you are having “msgbox” replace it with.. sh.Popup “message content”, 5, “msg header”, (0+4

 the above line will show the message content for 5 seconds(and vanishes after that).

The alert-box’s header will have “header info”. Last parameter(0+4 is actually two things. 0 -> show OK button in the alertBox 48 -> “!” icon… if you use 64 u will see X icon instead BTW… since u need the message to be displayed

February 14, 2008 Posted by quicktestprofessional | QTP Tips and Faqs | AOM, Automation Testing, Excel Automation, QTP, QTP Additional Faqs, QTP AOM, VBS, VBScripting, word automation | 2 Comments

QTP Tips and   Faqs

This document gives answer to some FAQ and also provides tips on certain aspects of QTP. 

Data Table Two Types of data tables

Page 25: QTP+Questions&Answers

Global data sheet: Accessible to all the actions

Local data sheet: Accessible to the associated action only

Usage:

DataTable(”Column Name”,dtGlobalSheet) for Global data sheet DataTable(”Column Name”,dtLocalSheet) for Local data sheet

If we change any thing in the Data Table at Run-Time the data is changed only in the run-time data table. The run-time data table is accessible onlythrough then test result. The run-time data table can also be exported using DataTable.Export or DataTable.ExportSheetHow can i save the changes to my DataTable in the test itself?

Well QTP does not allow anything for saving the run time changes to the actual data sheet. The only work around is to share thespreadsheet and then access it using the Excel COM Api’s.

How can i check if a parameter exists in DataTable or not?

The best way would be to use the below code:

code:

on error resume next val=DataTable(”ParamName”,dtGlobalSheet) if err.number<> 0 then    ‘Parameter does not exist else    ‘Parameter exists end if

How can i make some rows colored in the data table?

Well you can’t do it normally but you can use Excel COM API’s do the same. Below code will explain some expects of Excel COM APIs

code:

Set xlApp=Createobject(”Excel.Application”) set xlWorkBook=xlApp.workbooks.add set xlWorkSheet=xlWorkbook.worksheets.add

Page 26: QTP+Questions&Answers

xlWorkSheet.Range(”A1:B10″).interior.colorindex = 34 ‘Change the color of the cells xlWorkSheet.Range(”A1:A10″).value=”text” ‘Will set values of all 10 rows to “text” xlWorkSheet.Cells(1,1).value=”Text” ‘Will set the value of first row and first col

rowsCount=xlWorkSheet.Evaluate(”COUNTA(A:A)”) ‘Will count the # of rows which have non blank value in the column A colsCount=xlWorkSheet.Evaluate(”COUNTA(1:1)”) ‘Will count the # of non blank columns in 1st row

xlWorkbook.SaveAs “C:\Test.xls” xlWorkBook.Close Set xlWorkSheet=Nothing Set xlWorkBook=Nothing set xlApp=Nothing

SMART IdentificationSmart Identification is nothing but an algorithm used by QTP when it is not able to recognize one of the object. A very generic example as per theQTP manual would be, A photograph of a 8 year old girl and boy and QTP records identification properties of that girl when she was 8, now when

both are 10 years old then QTP would not be able to recognize the girl. But there is something that is still the same, that is there is only one girl in

the photograph. So it kind of PI (Programmed intelligence) not AI.

When should i use SMART Identification?

Something that people don’t think about too much. But the thing is that you should disable SI while creating your test cases. So that youare able to recognize the objects that are dynamic or inconsistent in their properties. When the script has been created, the SI should be enabled,so that the script does not fail in case of small changes. But the developer of the script should always check for the test results to verify if the SI

feature was used to identify a object or not. Sometimes SI needs to be disabled for particular objects in the OR, this is advisable when you use

SetTOProperty to change any of the TO properties of an object and especially ordinal identifiers like index, location and creationtime.

Descriptive Programming

Descriptive programming is nothing but a technique using which operations can be performed on the AUT object which are not present in the OR.

Page 27: QTP+Questions&Answers

Recovery ScenariosWhat is a Recovery Scenario?

Recovery scenario gives you an option to take some action for recovering from a fatal error in the test. The error could range in fromoccasional to typical errors. Occasional error would be like “Out of paper” popup error while printing something and typical errors would be like”object is disabled” or “object not found”. A test case have more then one scenario associated with it and also have the priority or order in which it

should be checked.

What does a Recovery Scenario consists of?

Trigger: Trigger is nothing but the cause for initiating the recovery scenario. It could be any popup window, any test error, particular stateof an object or any application error.

Action: Action defines what needs to be done if scenario has been triggered. It can consist of a mouse/keyboard event, close application, call arecovery function defined in library file or restart windows. You can have a series of all the specified actions.

Post-recovery operation: Basically defined what need to be done after the recovery action has been taken. It could be to repeat the step, moveto next step etc….

When to use a Recovery Scenario and when to us on error resume next?

Recovery scenarios are used when you cannot predict at what step the error can occur or when you know that error won’t occur in yourQTP script but could occur in the world outside QTP, again the example would be “out of paper”, as this error is caused by printer device driver. “Onerror resume next” should be used when you know if an error is expected and dont want to raise it, you may want to have different actions

depending upon the error that occurred. Use err.number & err.description to get more details about the error.

Library Files or VBScript FilesHow do we associate a library file with a test ?

Library files are files containing normal VBScript code. The file can contain function, sub procedure, classes etc…. You can also use executefilefunction to include a file at run-time also. To associate a library file with your script go to Test->Settings… and add your library file to resourcestab.

When to associate a library file with a test and when to use execute file?

When we associate a library file with the test, then all the functions within that library are available to all the actions present in the test. Butwhen we use Executefile function to load a library file, then the function are available in the

Page 28: QTP+Questions&Answers

action that called executefile. By associated a library toa test we share variables across action (global variables basically), using association also makes it possible to execute code as soon as the script

runs because while loading the script on startup QTP executes all the code on the global scope. We can use executefile in a library file associated

with the test to load dynamic files and they will be available to all the actions in the test.

Test and Run-time ObjectWhat is the difference between Test Objects and Run Time Objects ?

Test objects are basic and generic objects that QTP recognize. Run time object means the actual object to which a test object maps.

Can i change properties of a test object

Yes. You can use SetTOProperty to change the test object properties. It is recommended that you switch off the Smart Identification for theobject on which you use SetTOProperty function.

Can i change properties of a run time object?

No (but Yes also). You can use GetROProperty(”outerText”) to get the outerText of a object but there is no function like SetROProperty tochange this property. But you can use WebElement().object.outerText=”Something” to change the property.

Action & FunctionsWhat is the difference between an Action and a function?

Action is a thing specific to QTP while functions are a generic thing which is a feature of VB Scripting. Action can have a object repositoryassociated with it while a function can’t. A function is just lines of code with some/none parameters and a single return value while an action canhave more than one output parameters.

Where to use function or action?

Well answer depends on the scenario. If you want to use the OR feature then you have to go for Action only. If the functionality is not about anyautomation script i.e. a function like getting a string between to specific characters, now this is something not specific to QTP and can be done onpure VB Script, so this should be done in a function and not an action. Code specific to QTP can also be put into an function using DP. Decision of

using function/action depends on what any one would be comfortable using in a given situation.

Page 29: QTP+Questions&Answers

Checkpoint & Output valueWhat is checkpoint?

Checkpoint is basically a point in the test which validates for truthfulness of a specific things in the AUT. There are different types ofcheckpoints depending on the type of data that needs to be tested in the AUT. It can be text, image/bitmap, attributes, XML etc….

What’s the difference between a checkpoint and output value?

Checkpoint only checks for the specific attribute of an object in AUT while Output value can output those attributes value to a column in datatable.

How can i check if a checkpoint passes or not?code:

chk_PassFail = Browser(…).Page(…).WebEdit(…).Check (Checkpoint(”Check1″)) if chk_PassFail then    MsgBox “Check Point passed” else    MsgBox “Check Point failed” end if

My test fails due to checkpoint failing, Can i validate a checkpoint without my test failing due to checpoint failure?code:

Reporter.Filter = rfDisableAll ‘Disables all the reporting stuff chk_PassFail = Browser(…).Page(…).WebEdit(…).Check (Checkpoint(”Check1″)) Reporter.Filter = rfEnableAll ‘Enable all the reporting stuff if chk_PassFail then    MsgBox “Check Point passed” else    MsgBox “Check Point failed” end if

 EnvironmentHow can i import environment from a file on disk

Environment.LoadFromFile “C:\Env.xml”

How can i check if a environment variable exist or not?

When we use Environment(”Param1″).value then QTP expects the environment variable to be already defined. But when we

Page 30: QTP+Questions&Answers

useEnvironment.value(”Param1″) then QTP will create a new internal environment variable if it does not exists already. So to be sure that variable existin the environment try using Environment(”Param1″).value.

How to connect to a database?code:

Const adOpenStatic = 3 Const adLockOptimistic = 3 Const adUseClient = 3 Set objConnection = CreateObject(”ADODB.Connection”) Set objRecordset = CreateObject(”ADODB.Recordset”) objConnection.Open “DRIVER={Microsoft ODBC for Oracle};UID=<UID>;PWD=<PWD>” objRecordset.CursorLocation = adUseClient objRecordset.CursorType = adopenstatic objRecordset.LockType = adlockoptimistic ObjRecordset.Source=”select field1,field2 from testTable” ObjRecordset.ActiveConnection=ObjConnection ObjRecordset.Open ‘This will execute your Query If ObjRecordset.recordcount>0 then         Field1 = ObjRecordset(”Field1″).Value         Field2 = ObjRecordset(”Field2″).Value End if

Running stored procedures from QTP 

Public Function BIP_sqlRunStoredProcedure (sSProcName, sParameter1, sParameter2, sParameter3)‘ Create the database objectSet oADO_CMD = CreateObject(”ADODB.Command”)

‘Get connection stringsConnectionStr = Environment(”SQL_ConnectionStr”)‘ Activate the connectionoADO_CMD.ActiveConnection = sConnectionStr

‘ Set the command type to Stored ProceduresoADO_CMD.CommandType = 4oADO_CMD.CommandText = sSProcName

‘ Define Parameters for the stored procedureoADO_CMD.Parameters.Refresh‘ The order of input output values is the same order as defined in the stored procedure

‘Based on the qty of parameters (if any) for this sproc …‘This maps to the [optional] aspect of the function - not all sprocs have parameters.‘Note - in the ADO object model / Parameters collection (0) is reserved for the return value; the first parameter therefore is (1).If “” <> sParameter1 Then‘ Pass FIRST input value [optional]

Page 31: QTP+Questions&Answers

oADO_CMD.Parameters(1).Value = sParameter1‘msgbox oADOConnection.Parameters(1).Name +vbcr+ oADOConnection.Parameters(1).Value ‘DEBUG

If “” <> sParameter2 Then‘ Pass SECOND input value [optional]oADO_CMD.Parameters(2).Value = sParameter2‘msgbox oADOConnection.Parameters(2).Name +vbcr+ oADOConnection.Parameters(2).Value ‘DEBUG

If “” <> sParameter3 Then‘ Pass THIRD input value [optional]oADO_CMD.Parameters(3).Value = sParameter3‘msgbox oADOConnection.Parameters(3).Name +vbcr+ oADOConnection.Parameters(3).Value ‘DEBUGEnd IfEnd IfEnd If

‘ Execute the stored procedureoADO_CMD.Execute()

‘Clean up objectsSet oADO_CMD = Nothing

End Function

February 14, 2008 Posted by quicktestprofessional | Running stored procedures from QTP | AOM, Automation Testing, Excel Automation, QTP, QTP AOM, Running stored procedures from QTP, VBS, VBScripting, word automation | No Comments

Running stored procedures from   QTP

Running stored procedures from QTP 

Public Function BIP_sqlRunStoredProcedure (sSProcName, sParameter1, sParameter2, sParameter3)

‘ Create the database objectSet oADO_CMD = CreateObject(”ADODB.Command”)

‘Get connection stringsConnectionStr = Environment(”SQL_ConnectionStr”)‘ Activate the connectionoADO_CMD.ActiveConnection = sConnectionStr

‘ Set the command type to Stored ProceduresoADO_CMD.CommandType = 4oADO_CMD.CommandText = sSProcName

Page 32: QTP+Questions&Answers

‘ Define Parameters for the stored procedureoADO_CMD.Parameters.Refresh‘ The order of input output values is the same order as defined in the stored procedure

‘Based on the qty of parameters (if any) for this sproc …‘This maps to the [optional] aspect of the function - not all sprocs have parameters.‘Note - in the ADO object model / Parameters collection (0) is reserved for the return value; the first parameter therefore is (1).If “” <> sParameter1 Then‘ Pass FIRST input value [optional]oADO_CMD.Parameters(1).Value = sParameter1‘msgbox oADOConnection.Parameters(1).Name +vbcr+ oADOConnection.Parameters(1).Value ‘DEBUG

If “” <> sParameter2 Then‘ Pass SECOND input value [optional]oADO_CMD.Parameters(2).Value = sParameter2‘msgbox oADOConnection.Parameters(2).Name +vbcr+ oADOConnection.Parameters(2).Value ‘DEBUG

If “” <> sParameter3 Then‘ Pass THIRD input value [optional]oADO_CMD.Parameters(3).Value = sParameter3‘msgbox oADOConnection.Parameters(3).Name +vbcr+ oADOConnection.Parameters(3).Value ‘DEBUGEnd IfEnd IfEnd If

‘ Execute the stored procedureoADO_CMD.Execute()

‘Clean up objectsSet oADO_CMD = Nothing

End Function

How to send a key command to a Web object

Some Web objects will perform actions when certain key commands, such as ALT+RETURN, are entered. These Web objects do not have a type method associated with them that can be used to replay these keys. How can the key combination be replayed?

Solution: Use the Windows Scripting SendKeys method 1. Create a WScript.Shell object.2. Activate the browser in which you want to execute the keys.3. Use the SendKeys method to type the key combination. Example:‘ This code executes the CTRL+F key combination (search) on a browser.

Page 33: QTP+Questions&Answers

Set WshShell = CreateObject(”WScript.Shell”)WshShell.AppActivate “Put the label of the browser” ‘ Activate the browser windowwait(3)WshShell.SendKeys “^f” ‘ The caret (^) represents the CTRL key.wait(2) object.SendKeys(string) object A WshShell object.string The string value indicating the keystroke(s) you want to send.The SendKeys method will send keystroke(s) to the active window. To send a single character (for example, x), use “x” as the string argument. To send multiple characters (for example, abc), use “abc” as the string argument. You can also send special characters such as SHIFT, CTRL, and ALT, which are represented by the plus sign (+), the caret (^), and the percent sign (%), respectively.For more information on the SendKeys method and other special keys, such as the backspace or a function key, please refer to the MSDN SendKeys Method page. ====================================================================================================‘ Name: KeyboardShortCut‘‘ Input:‘   ByRef Key As Variant - The keyboard key to be typed.‘   ByRef Pane As Variant - The window/pane to type in.‘ Purpose: To type keyboard input onto the open window.‘====================================================================================================Function KeyboardShortCut (Key)    dim obj    Set obj = Window(”Window Name” ).WinObject(”Object”)    obj.type Key    Environment(”LastResult”) = “Success”End FunctionSolution2: Pressing Function keys should be recorded automatically Directly recording on the application and pressing the Function Keys (F1, F2, etc.) should generate code for replay. Example:‘Here is an example recorded against Notepad:   Window(”Notepad”).Activate   Window(”Notepad”).WinEditor(”Edit”).Type micF5 If the above does not work, then you can use DeviceReplay to simulate pressing keyboard keys. Example:‘Here is an example that does the same thing above, but used DeviceReplay.   Set obj = CreateObject(”Mercury.DeviceReplay”)   Window(”Notepad”).Activate   obj.PressKey 63

Page 34: QTP+Questions&Answers

Note:The PressKey method uses the appropriate ASCII or IBM Scan Code value for the key. “63″ is the IBM Scan Code value for F5.

The following code popup a dialog with a edit box for a password entry when it run from the QTP

Set objForm = DotNetFactory.CreateInstance(”System.Windows.Forms.Form”, “System.Windows.Forms”)Set objBtn1 = DotNetFactory.CreateInstance(”System.Windows.Forms.Button”, “System.Windows.Forms”)Set objEdit1 = DotNetFactory.CreateInstance(”System.Windows.Forms.TextBox”, “System.Windows.Forms”)x=80y=40Set p1 = DotNetFactory.CreateInstance(”System.Drawing.Point”,”System.Drawing”,x,y) ‘This will provide the locations(X,Y) for the controlsSet lbl= DotNetFactory.CreateInstance(”System.Windows.Forms.Label”,”System.Windows.Forms”)lbl.Text=”Enter Password”lbl.Location=p1objForm.Controls.Add(lbl)p1.Y=CInt(lbl.Height)+40objEdit1.Location=p1objForm.Controls.Add(lbl)

objEdit1.UseSystemPasswordChar=true’To set the password character From system

objForm.Controls.Add(objEdit1)objBtn1.Text=”OK”

p1.Y=Cint(p1.Y)+CInt(objEdit1.Height)+20objBtn1.Location=p1

objForm.CancelButton=objBtn1

objForm.Controls.Add(objBtn1)

objForm.StartPosition=CenterScreenobjForm.Text=”Mohan kakarla”objForm.ShowDialog

msgbox “The Password You have Entered Is: “&objEdit1.Text

Page 35: QTP+Questions&Answers

Author: Mohan Kumar Kakarla

March 15, 2008 Posted by quicktestprofessional | DotNetFactory, Uncategorized | DotNetFactory, Prompt Dialog For Password Entry In QTP, Prompt Dialog For Password Entry In QTP with help of Do, QTP | No Comments

OpenFileDialog In QTP with help of   DotNetFactory

 Set fd = DotNetFactory.CreateInstance(”System.Windows.Forms.OpenFileDialog”, “System.Windows.Forms”)fd.InitialDirectory=”c:\\”fd.Filter=”txt files (*.txt)|*.txt |All files (*.*) |*.*”fd.RestoreDirectory=truefd.FilterIndex=2fd.ShowDialog()msgbox fd.FileName

March 15, 2008 Posted by quicktestprofessional | DotNetFactory, Uncategorized | DotNetFactory, OpenFileDialog In QTP, QTP | 1 Comment

Prompt Dialog with Radio buttons in QTP with help of   DotNetFactory

The following code popup a dialog with 2 radi button to select an option when it run from the QTP

Set objForm = DotNetFactory.CreateInstance(”System.Windows.Forms.Form”, “System.Windows.Forms”)

Set objRd1 = DotNetFactory.CreateInstance(”System.Windows.Forms.RadioButton”, “System.Windows.Forms”)Set objRd2 = DotNetFactory.CreateInstance(”System.Windows.Forms.RadioButton”, “System.Windows.Forms”)Set objGb = DotNetFactory.CreateInstance(”System.Windows.Forms.GroupBox”, “System.Windows.Forms”)Set objBtn2 = DotNetFactory.CreateInstance(”System.Windows.Forms.Button”, “System.Windows.Forms”)x=10y=10Set p1 = DotNetFactory.CreateInstance(”System.Drawing.Point”,”System.Drawing”,x,y) ‘This will provide the locations(X,Y) for the controls

objRd1.Text=”Radio1″objGb.Location=p1

Page 36: QTP+Questions&Answers

p1.Y=30objRd1.Location=p1p1.Y=CInt(objRd1.Height)+CInt(objRd1.Top)+10objRd2.Location=p1objRd2.Text=”Radio2″objGb.Text=”Select The Radio Button”objGb.Controls.Add(objRd1)objGb.Controls.Add(objRd2)objBtn2.Text=”OK”p1.X=60

p1.Y=CInt(objGb.Height)+20objBtn2.Location=p1objForm.CancelButton=objBtn2

objForm.Controls.Add(objGb)objForm.Controls.Add(objBtn2)objForm.StartPosition=CenterScreenobjForm.Text=”Mohan kakarla”objForm.ShowDialogIf objRd1.Checked Thenmsgbox “You have selected Radio 1″elseif objRd2.Checked Thenmsgbox “You have selected Radio 2″elsemsgbox “No Radio button was selected”End If

Author: Mohan Kumar Kakarla

March 15, 2008 Posted by quicktestprofessional | DotNetFactory, Uncategorized | DotNetFactory, QTP, radio buttons in a dialog box | 1 Comment

Prompt for password entry and hide while it is being   typed

some times we need to prompt input box for a password and we need to  hide a password while it is being typed. But it is not possible with normal VBScript . we can use the AOM for IE with VBScript to do this.

Following is the code

strPw = GetPassword( “Please enter your password:” )msgbox  “Your password is: ” & strPw

Page 37: QTP+Questions&Answers

Function GetPassword( myPrompt )‘ This function uses Internet Explorer to‘ create a dialog and prompt for a password.

    Dim objIE    ‘ Create an IE object    Set objIE = CreateObject( “InternetExplorer.Application” )    ‘ specify  the IE  settings    objIE.Navigate “about:blank”    objIE.Document.Title = “Password”    objIE.ToolBar        = False    objIE.Resizable      = False    objIE.StatusBar      = False    objIE.Width          = 300    objIE.Height         = 180    ‘ Center the dialog window on the screen    With objIE.Document.ParentWindow.Screen        objIE.Left = (.AvailWidth  - objIE.Width ) \ 2        objIE.Top  = (.Availheight - objIE.Height) \ 2    End With      ‘ Insert the HTML code to prompt for a password    objIE.Document.Body.InnerHTML = “<DIV align=”"center”"><P>” & myPrompt _                                  & “</P>” & vbCrLf _                                  & “<P><INPUT TYPE=”"password”" SIZE=”"20″” ” _                                  & “ID=”"Password”"></P>” & vbCrLf _                                  & “<P><INPUT TYPE=”"hidden”" ID=”"OK”" ” _                                  & “NAME=”"OK”" VALUE=”"0″”>” _                                  & “<INPUT TYPE=”"submit”" VALUE=”" OK “” ” _                                  & “OnClick=”"VBScript:OK.Value=1″”></P></DIV>”    ‘ Make the window visible    objIE.Visible = True    ‘ Wait till the OK button has been clicked    Do While objIE.Document.All.OK.Value = 0        WScript.Sleep 200    Loop    ‘ Read the password from the dialog window    GetPassword = objIE.Document.All.Password.Value    ‘ Close and release the object    objIE.Quit    Set objIE = NothingEnd Function

The code will create the screen like this

Page 38: QTP+Questions&Answers

Reference: Robvan der Woude

February 15, 2008 Posted by quicktestprofessional | VBScript and IE Automation | hide a password, hide a password while it is being typed, QTP, VBScript | 2 Comments

Run an .exe file and wait till it   finish

To run path\abc .exe and wait to contunie with next statement in the .vbs-file until after abc.exe has finished.

add the bWaitOnReturn  parameter to the Run statement …

object.Run strCommand, [intWindowStyle], [bWaitOnReturn]

February 15, 2008 Posted by quicktestprofessional | Uncategorized | | No Comments

Descriptive   programming

Descriptive programming

When and Why to use Descriptive programming?

Below are some of the situations when Descriptive Programming can be considered useful:

1. The objects in the application are dynamic in nature and need special handling to identify the object. The best example would be of clicking a link which changes according to the user of the application, Ex. “Logout <>”.

2. When object repository is getting huge due to the no. of objects being added. If the size of Object repository increases too much then it decreases the performance of QTP while recognizing a object.

Page 39: QTP+Questions&Answers

3. When you don’t want to use object repository at all. Well the first question would be why not Object repository? Consider the following scenario which would help understand why not Object repository Scenario 1: Suppose we have a web application that has not been developed yet. Now QTP for recording the script and adding the objects to repository needs the application to be up, that would mean waiting for the application to be deployed before we can start of with maki! ng QTP scripts. But if we know the descriptions of the objects that will be created then we can still start off with the script writing for testing Scenario 2: Suppose an application has 3 navigation buttons on each and every page. Let the buttons be “Cancel”, “Back” and “Next”. Now recording action on these buttons would add 3 objects per page in the repository. For a 10 page flow this would mean 30 objects which could have been represented just by using 3 objects. So instead of adding these 30 objects to the repository we can just write 3 descriptions for the object and use it on any page.

 4. Modification to a test case is needed but the Object repository for the same is Read only or in shared mode i.e. changes may affect other scripts as well. 5. When you want to take action on similar type of object i.e. suppo! se we have 20 textboxes on the page and there names are in the form txt_1, txt_2, txt_3 and so on. Now adding all 20 the Object repository would not be a good programming approach. How to use Descriptive programming? There are two ways in which descriptive programming can be used

1. By creating properties collection object for the description.

2. By giving the description in form of the string arguments.

1. By creating properties collection object for the description. To use this method you need first to create an empty description Dim obj_Desc ‘Not necessary to declare

 Set obj_Desc = Description.Create

Now we have a blank description in “obj_Desc”.

Each description has 3 properties “Name”, “Value” and “Regular Expression”.

obj_Desc(“html tag”).value= “INPUT”

When you use a property name for the first time the property is added to the collection and when you use it again the property is modified. By default each property that is defined is a regular expression. Suppose if we have the following

description obj_Desc(“html tag”).value= “INPUT” obj_Desc(“name”).value= “txt.*”

This would mean an object with html tag as INPUT and name starting with txt. Now actually that “.*” was considered as regular expression. So, if you! want the property “name” not to be recognized as a regular expression then you need to set the “regularexpression” property as FALSE

Page 40: QTP+Questions&Answers

obj_Desc(“html tag”).value= “INPUT”

obj_Desc(“name”).value= “txt.*” o

bj_Desc(“name”).regularexpression= “txt.*”

This is how of we create a description. Now below is the way we can use it

Browser(“Browser”).Page(“Page”).WebEdit(obj_Desc).set “Test”

When we say .WebEdit(obj_Desc) we define one more property for our description that was not earlier defined that is it’s a text box (because QTPs WebEdit boxes map to text boxes in a web page). If we know that we have more than 1 element with same description on the page then we must define “index” property for the that description Consider the HTML code given below

  !

Now the html code has two objects with same description. So distinguish between these 2 objects we will use the “index” property.

Here is the description for both the object

For 1st textbox:

obj_Desc(“! html tag”).value= “INPUT”

obj_Desc(“name”).value= “txt_Name”

obj_Desc(“index”).value= “0”

For 2nd textbox:

 obj_Desc(“html tag”).value= “INPUT”

 obj_Desc(“name”).value= “txt_Name”

obj_Desc(“index”).value= “1”

! Consider the HTML Code given below:

We can use the same description for both the objects and still distinguish between both of them

obj_Desc(“html tag”).value= “INPUT”

Page 41: QTP+Questions&Answers

obj_Desc(“name”).value= “txt_Name”

When I want to refer to the textbox then I! will use the inside a WebEdit object and to refer to the radio button I will use the description object with the WebRadioGroup object.

Browser(“Browser”).Page(“Page”).WebEdit(obj_Desc).set “Test” ‘

Refers to the text box Browser(“Browser”).Page(“Page”).WebRadioGroup(obj_Desc).set “Test” ‘

Refers to the radio button But if we use WebElement object for the description then we must define the “index” property because for a webelement the current description would return two objects. Hierarchy of test description: When using programmatic descriptions from a specific point within a test object hierarchy, you must continue to use programmatic descriptions from that point onward within the same statement. If you specify a test object by its object repository name after other objects in the hierarchy have been described using programmatic descriptions, QuickTest cannot identify the object.

For example, you can use Browser(Desc1).Page(Desc1).Link(desc3),

since it uses programmatic descriptions throughout the entire test object hierarchy. You can also use

Browser(”Index”).Page(Desc1).Link(desc3),

since it uses programmatic descriptions from a certain point in the description (starting from the Page object description). However, you cannot use

Browser(Desc1).Page(Desc1).Link(”Example1″),

since it uses programmatic descriptions for the Browser and Page objects but then attempts to use an object repository name for the Link test object (QuickTest tries to locate the Link object based on its name, but cannot locate it in the repository because the parent objects were specified using programmatic descriptions).

Getting Child Object: We can use description object to get all the objects on the page that matches that specific description. Suppose we have to check all the checkboxes present on a web page. So we will first create an object description for a checkboxe and then get all the checkboxes from the page

Dim obj_ChkDesc

Set obj_ChkDesc=Description.Create

obj_ChkDesc(“html tag”).value = “INPUT”

Page 42: QTP+Questions&Answers

obj_ChkDesc(“type”).value = “checkbox”

Dim allCheckboxes, singleCheckBox

Set allCheckboxes = Browse(“Browser”).Page(“Page”).ChildObjects(obj_ChkDesc)

For each singleCheckBox in allCheckboxes singleCheckBox.Set “ON” Next

 The above code will check all the check boxes present on the page.!

To get all the child objects we need to specify an object description i.e. we can’t use the string arguments that will be discussed later in the 2nd way of using the programming description. Possible Operation on Description Object Consider the below code for all the solutions

Dim obj_ChkDesc

Set obj_ChkDesc=Description.Create

obj_ChkDesc(“html tag”).value = “INPUT”

obj_ChkDesc(“type”).value = “checkbox”

Q: How to get the no. of description defined in a collection

A: obj_ChkDesc.Count ‘Will return 2 in our case

Q: How to remove a description from the collection

A: obj_ChkDesc.remove “html tag” ‘would delete the html tag property from the collection

Q: How do I check if property exists or not in the collection? !

 A: The answer is that it’s not possible. Because whenever we try to access a property which is not defined its automatically added to the collection. The only way to determine is to check its value that is use a if statement “

if obj_ChkDesc(“html tag”).value = empty then”.

 Q: How to browse through all the properties of a properties collection?

 A: Two ways 1st:

For each desc in obj_ChkDesc

Page 43: QTP+Questions&Answers

Name=desc.Name

 Value=desc.Value R

E = desc.regularexpression

Next

2nd:

For i=0 to obj_ChkDesc.count - 1

 Name= obj_ChkDesc(i).Name

Value= obj_ChkDesc(i).Value

RE = obj_ChkDesc(i).regularexpression

Next

2. By giving the description in form of the string arguments. You can describe an object directly in a statement by specifying property:=value pairs describing the object instead of specifying an object’s name.

The general syntax is:

TestObject(”PropertyName1:=PropertyValue1″, “…” , “PropertyNameX:=PropertyValueX”)

TestObject—the test object class could be WebEdit, WebRadioGroup etc….

PropertyName:=PropertyValue—the test object property and its value.

Each property:=value pair should be separated by commas and quotation marks. Note that you can enter a variable name as the property value if you want to find an object based on property values you retrieve during a run session. Consider the HTML Code given below:

 Now to refer to the textbox the statement would be as given below

Browser(“Browser”).Page(“Page”).WebEdit(“Name:=txt_Name”,”html tag:=INPUT”).set “Test”

And to refer to the radio button the statement would be as given below

Page 44: QTP+Questions&Answers

Browser(“Browser”).Page(“Page”).WebRadioGroup(“Name:=txt_Name”,”html tag:=INPUT”).set “Test”

If we refer to them as a web element then we will have to distinguish between the 2 using the index property Browser(“Browser”).Page(“Page”).WebElement(“Name:=txt_Name”,”html tag:=INPUT”,”Index:=0”).set “Test” ‘

Refers to the textbox

 Browser(“Browser”).Page(“Page”).WebElement(“Name:=txt_Name”,”html tag:=INPUT”,”Index:=1”).set “Test” ‘

 Refers to the radio button

 Reference: 1. “Mercury QuickTest Professional, User’s Guide, Version 8.0.1”

                     2. Tarun lalwani ’s document about D.P