Custom Search

Saturday, October 6, 2007

How do you identify which files are loaded in the GUI map?

 

    1. The GUI Map Editor has a drop down "GUI File" displaying all the GUI Map files loaded into the memory.


--
WIN RUNNER

What different actions are performed by find and show button?

 

    1. To find a particular object in the GUI Map file in the application, select the object and click the Show window. This blinks the selected object.
    2. To find a particular object in a GUI Map file click the Find button, which gives the option to select the object. When the object is selected, if the object has been learned to the GUI Map file it will be focused in the GUI Map file.


--
WIN RUNNER

How do you find an object in an GUI map.

 

    1. The GUI Map Editor is been provided with a Find and Show Buttons.

                                                             i.      To find a particular object in the GUI Map file in the application, select the object and click the Show window. This blinks the selected object.

                                                          ii.      To find a particular object in a GUI Map file click the Find button, which gives the option to select the object. When the object is selected, if the object has been learned to the GUI Map file it will be focused in the GUI Map file.



--
WIN RUNNER

What is the disadvantage of loading the GUI maps through start up scripts?

 

    1. If we are using a single GUI Map file for the entire AUT then the memory used by the GUI Map may be much high.
    2. If there is any change in the object being learned then WinRunner will not be able to recognize the object, as it is not in the GUI Map file loaded in the memory. So we will have to learn the object again and update the GUI File and reload it.


--
WIN RUNNER

How do you load GUI map?

 

    1. We can load a GUI Map by using the GUI_load command.

 

    1. Syntax: GUI_load(<file_name>);


--
WIN RUNNER

What is the purpose of set_window command?

 

    1. Set_Window command sets the focus to the specified window. We use this command to set the focus to the required window before executing tests on a particular window.

 

    1. Syntax: set_window(<logical name>, time);

c.     The logical name is the logical name of the window and time is the time the execution has to wait till it gets the given window into focus.



--
WIN RUNNER

When you create GUI map do you record all the objects of specific objects?

 

    1. If we are learning a window then WinRunner automatically learns all the objects in the window else we will we identifying those object, which are to be learned in a window, since we will be working with only those objects while creating scripts.


--
WIN RUNNER

How do you view the contents of the GUI map?

 

    1. GUI Map editor displays the content of a GUI Map. We can invoke GUI Map Editor from the Tools Menu in WinRunner. The GUI Map Editor displays the various GUI Map files created and the windows and objects learned in to them with their logical name and physical description.


--
WIN RUNNER

What is the different between GUI map and GUI map files?

 

    1. The GUI map is actually the sum of one or more GUI map files. There are two modes for organizing GUI map files.

                                                             i.      Global GUI Map file: a single GUI Map file for the entire application

                                                          ii.      GUI Map File per Test: WinRunner automatically creates a GUI Map file for each test created.

    1. GUI Map file is a file which contains the windows and the objects learned by the WinRunner with its logical name and their physical description.


--
WIN RUNNER

If the object does not have a name then what will be the logical name?

 

    1. If the object does not have a name then the logical name could be the attached text.


--
WIN RUNNER

What do you mean by the logical name of the object.

 

    1. An object's logical name is determined by its class. In most cases, the logical name is the label that appears on an object.


--
WIN RUNNER

What are the reasons that WinRunner fails to identify an object on the GUI?

 

    1. WinRunner fails to identify an object in a GUI due to various reasons.

                                                             i.      The object is not a standard windows object.

                                                          ii.      If the browser used is not compatible with the WinRunner version, GUI Map Editor will not be able to learn any of the objects displayed in the browser window.


--
WIN RUNNER

What is the purpose of loading WinRunner Add-Ins?

 

    1. Add-Ins are used in WinRunner to load functions specific to the particular add-in to the memory. While creating a script only those functions in the add-in selected will be listed in the function generator and while executing the script only those functions in the loaded add-in will be executed else WinRunner will give an error message saying it does not recognize the function.


--
WIN RUNNER

What are the different modes of recording?

 

    1. There are two type of recording in WinRunner.

                                                             i.      Context Sensitive recording records the operations you perform on your application by identifying Graphical User Interface (GUI) objects.    

                                                          ii.      Analog recording records keyboard input, mouse clicks, and the precise x- and y-coordinates traveled by the mouse pointer across the screen.


--
WIN RUNNER

How you integrated your automated scripts from Test Director?

 

    1. When you work with Win Runner, you can choose to save your tests directly to your Test Director database or while creating a test case in the Test Director we can specify whether the script in automated or manual. And if it is automated script then TestDirector will build a skeleton for the script that can be later modified into one which could be used to test the AUT.


--
WIN RUNNER

What is the use of Test Director software?


 

    1. Test Director is Mercury Interactive software test management tool. It helps quality assurance personnel plan and organize the testing process. With Test Director you can create a database of manual and automated tests, build test cycles, run tests, and report and track defects. You can also create reports and graphs to help review the progress of planning tests, running tests, and tracking defects before a software release.

--
WIN RUNNER

How do you analyze results and report the defects?

 

 

    1. Following each test run, Win Runner displays the results in a report. The report details all the major events that occurred during the run, such as checkpoints, error messages, system messages, or user messages. If mismatches are detected at checkpoints during the test run, you can view the expected results and the actual results from the Test Results window. If a test run fails due to a defect in the application being tested, you can report information about the defect directly from the Test Results window. This information is sent via e-mail to the quality assurance manager, who tracks the defect until it is fixed.


--
WIN RUNNER

How do you run your test scripts?


 

    1. We run tests in Verify mode to test your application. Each time Win Runner encounters a checkpoint in the test script, it compares the current data of the application being tested to the expected data captured earlier. If any mismatches are found, Win Runner captures them as actual results.

--
WIN RUNNER

Have you performed debugging of the scripts?

 

    1. Yes, I have performed debugging of scripts. We can debug the script by executing the script in the debug mode. We can also debug script using the Step, Step Into, Step out functionalities provided by the Win Runner.


--
WIN RUNNER

How does Win Runner evaluate test results?

 

    1. Following each test run, Win Runner displays the results in a report. The report details all the major events that occurred during the run, such as checkpoints, error messages, system messages, or user messages. If mismatches are detected at checkpoints during the test run, you can view the expected results and the actual results from the Test Results window.


--
WIN RUNNER

Have you created test scripts and what is contained in the test scripts?


 

    1. Yes I have created test scripts. It contains the statement in Mercury Interactive Test Script Language (TSL). These statements appear as a test script in a test window. You can then enhance your recorded test script, either by typing in additional TSL functions and programming elements or by using Win Runner's visual programming tool, the Function Generator.

--
WIN RUNNER

How does Win Runner recognize objects on the application?

 a) Win Runner uses the GUI Map file to recognize objects on the application. When Win Runner runs a test, it uses the GUI map to locate objects. It reads an object's description in the GUI map and then looks for an object with the same properties in the application being tested.



--
WIN RUNNER

What in contained in the GUI map?

 

 

    1. Win Runner stores information it learns about a window or object in a GUI Map. When Win Runner runs a test, it uses the GUI map to locate objects. It reads an object's description in the GUI map and then looks for an object with the same properties in the application being tested. Each of these objects in the GUI Map file will be having a logical name and a physical description.
    2. There are 2 types of GUI Map files.

                                                             i.      Global GUI Map file: a single GUI Map file for the entire application

                                                           ii.      GUI Map File per Test: Win Runner automatically creates a GUI Map file for each test created.



--
WIN RUNNER

2) Explain Win Runner testing process?

a.    Win Runner testing process involves six main stages

                                                             i.      Create GUI Map File so that Win Runner can recognize the GUI objects in the application being tested

                                                           ii.      Create test scripts by recording, programming, or a combination of both. While recording tests, insert checkpoints where you want to check the response of the application being tested.

                                                         iii.      Debug Test: run tests in Debug mode to make sure they run smoothly

                                                        iv.      Run Tests: run tests in Verify mode to test your application.

                                                          v.      View Results: determines the success or failure of the tests.

                                                        vi.      Report Defects: If a test run fails due to a defect in the application being tested, you can report information about the defect directly from the Test Results window.

 
--
WIN RUNNER
 

1) How you used Win Runner in your project?

a.    Yes, I have been Win Runner for creating automates scripts for GUI, functional and regression testing of the AUT.

QTP Coding

Overview

1.1       About this document

This document defines the prescribed coding conventions and practices for Test Automation using Mercury Quick Test Professional. Since QTP uses VBScript as the scripting language,   most of the conventions are derived from Microsoft's conventions defined for VBScript.

The document provides a set of conventions and best practices for Mercury QTP, which can be used as a reference by the individual project teams to define their own standards by tailoring the recommendations.

This document is organized into the following sections:

·         Structure Conventions: standards to adhere to while writing and laying out(indenting) code.

·         Documentation Conventions: standards to adhere to while documenting code.

·         Naming Conventions: standards to adhere to while naming identifiers (Scripts, function names, variable names, etc.)

·         Recommendations: suggestions and rules-of-thumb that help avoid some common automation pitfalls.

 

1.2      Target Audience

This document is addressed to the following set of audience

§         Testers/developers involved in automation script development using Mercury QTP

§         Testers/developers involved in code reviews of Mercury QTP automation scripts.

 

1.3       Definitions

A convention is one of the following:

·         A standard (S) is a mandatory constraint on the content or format of something ( e.g., code, documentation).  You must follow standards unless you obtain a waiver from the Process Team and you document the deviation from the standard.

·         A guideline (G) is an optional constraint on the content or format of something ( e.g., code, documentation).  You should follow guidelines in most cases.  You must document any deviation from the guideline.

·         A recommendation (R) offers advice.   It is less constraining than either a standard or guideline.  You may follow or ignore recommendations as appropriate.   You need not document any deviations from recommendations.

 

Code Conventions

Code Organization

·         Keep modules to a manageable size.   Each module should be less than about 1000 lines, and contain a set of procedures that are related to each other.  If a module is becoming larger than 1000 lines, consider splitting it based on some functional criteria.

Rationale:   Small, cohesive modules are more manageable and easier to understand.  They also reduce sharing conflicts in version control tools.

·     Keep procedures to a manageable size.   Each procedure should be concise enough that its entire purpose can be easily expressed and understood.  One rule of thumb is that the well-commented procedure should fit on a printed page.   A more relevant rule when editing the code is that it fit on one screen in the development environment.

     Rationale:  Small procedures are easier to understand and verify.

Exception:  A single control structure (for example, a Select structure) may be unavoidably longer than the recommended procedure length.   In this case, the control structure should be placed in its own procedure, separate from other code, so as not to obscure the function of the code around it.

·     All script level variables should be defined at the beginning of the script.

 

Indentation

·         Use the indentation by setting 'Tab spacing' property to 4 characters (In QTP – Tools>Editor options).

Rationale:   Indentation improves readability.  Using the standard tab-stop indentation improves maintainability, allowing the indent level of blocks of code to be easily changed.

·         Use four spaces for each indent level.   The default tab spacing in VB is four spaces, and this should be maintained. 

Rationale:   Four spaces are enough to make the indentation level obvious, without taking up too much horizontal space.

·         While breaking up long lines, a spill-over indentation of 4 spaces should be used.

Characters per Line

Avoid lines longer than 80 characters. This rule also applies for documentation lines.

Rationale: Longer lines are more difficult to read.  Also, many terminals and tools do not handle longer lines well.

Use Line Continuation

To break your strings and/or code apart on multiple lines using the underscore character '_'.

 

"Break up long procedure declarations on to multiple lines with each parameter aligned".

Rationale:   This makes the code much easier to read and makes it less likely that maintenance will introduce new bugs.

 

Example :

Function CollectStats(sFileName, _
       iStartLine As Long, _
       iEndLine As Long) _

Blank Lines

Put a blank line between logical sections of a procedure.

Rationale:   This improves readability.

Example :

Sub ProcessData()

 

CheckPrecondition

 

DoFoo

DoFam

 

CheckPostcondition

 

End Sub

Comment:   If the method is long or violates other standards, it should be factored based on the logical sections described above.

Control Flow Statements

If...Then...Else Statements

The if-else class of statements should have the following form:

 

If – End If Statement

 

If (condition) Then

 

        Statements

 

End If       

 

 

If – else nested statements

If condition Then

 

    If condition Then

 

        statements

 

    Else

 

        statements

 

    End If

 

Else

 

    If condition Then

 

        statements

 

    Else

 

        statements

 

    End If

 

End If

 

If – elseif nested statements

 

If condition Then

 

    statements

 

ElseIf condition Then

 

    statements

 

Else

 

    statements

 

End If

While...WEnd Statements

while condition statement

 

while condition

 

   statements

 

Wend

 

 

 

 

 

 

 

 

 

 

 

 

Do... Loop Statements

             1> Do Until... Loop

Do Until condition

                         

    Statements

 

Loop 

 

2>Do...Loop, Do While...Loop

Do

 

    statements

 

    Do While condition                 

 

        statements

 

    Loop

 

Loop   Until condition

For...Next Statements

A For statement should have the following form

1>

for <initialization condition> To <update> statement

2>

for <initialization; condition> To <update>

 

    statements

 

    for <initialization; condition> To <update>

 

        statements

 

    Next          

 

Next

ForEach...Next Statement

A ForEach statement should have the following form

 

ForEach <element> in <block>

 

    statements

 

Next

Select Statement

A Select statement should have the following form

1>

Select Case <test expression>

 

    Case <expression> Statement       

      

    Case <expression> Statement

 

    Case Else Statement

 

End Select      

2>           

Select Case <test expression>

 

    Case <expression>

 

        Statements

 

    Case <expression>

 

        Statements

 

    Case Else  

 

        Statements

 

End Select      

 

With Statement

A With statement should have the following form

With Object

    Statements

End With

Documentation Conventions

The following Visual Basic comment standards provide a consistent approach to documenting the code.

Comment Formatting

Begin comments with '* (an apostrophe, an asterisk, and a space).  All VB comments start with an apostrophe and end with a line break.  This convention adds an asterisk and space before the actual comment text.

Rationale:   When viewing VB code, the apostrophe alone does distinguish the comment well from the code. The asterisk and space improves legibility by setting the comments off more clearly.

File Comments

Write a comment block at the top of each script/File.   The comment block will include the name of the module, a description of its purpose, its authors, and its revision history.  It should also contain version and copyright information, if appropriate.   Each entry in the revision history will include the date that the change was made, the author who made the change.

     Following is the example of the header:

'********************************************************************************************************

'* Copyright ©  2004, <team name>, Hyderabad.
'* This is UNPUBLISHED PROPRIETARY SOURCE CODE of <team name>;                                  '* The contents of this file may not be disclosed to third parties copied or duplicated in any     '* form, in whole or in part, without the prior written permission of <team name>.
'* ALL RIGHTS RESERVED.
'* Author:                               : Xxxxxxx xxx.
'* Project:                                     :  <Project Name>.
'* Filename:                       :  <File/Script/Action Name>
'* Created on:                              :  <Date dd/mm/yyyy>
'* File path:                        :  <Relative Path from the root of automation
'* Abstract                          : <purpose/content of the file/script/action>                                                                         '* Last modified date         :            -  
'* Last modified by            :            -
'********************************************************************************************************

Procedure Comments

Begin each procedure with a comment block.  The comment block shall precede the declaration accordingly, and contain a description of the procedure, including the reason why it is needed.   Following that should be a list of the pre-conditions and post-conditions necessary for its operation<optional>, a description of its parameters and return value, and possible errors which may occur.

Rationale: Well-commented procedures make the code easier to understand.

Example: 

'* Run the spell checker on the textbox.  This prevents
'* spelling errors from being stored and displayed to the
'* customers.

'* Pre conditions: Textbox has been filled
'* Post conditions: The data in the textbox may change if
'*   spelling corrections have occurred

'* Parameters:
'*   txtComments – Textbox  containing free-form text
'* Return Value:
'*   Boolean indicating whether spelling errors were found.

Function CheckSpelling ( txtComments )

1.4  Declaration Comments

Describe the abstraction of all declared constants, types, and variables, the meanings of which are not obvious from the name.   This includes both module- and procedure-level declarations.  Also, describe any constraints of the variables.

Rationale : This will make the code easier to understand and maintain.

Example :

Dim intPrevPos As Long '* Previous cursor position
                                    '* (0..MAXPOS)

1.5  General Comments

·  Do not comment obvious code . 

If the code is not obvious, then first see if you can rewrite the code so that the use of comments will be unnecessary.

Rationale : This will make the code easier to maintain.

Bad Example :

Dim lngConnectionCount       '* number of connections

·         Where practical, line up trailing comments .

Rationale : This will make the comments easier to see, compare, and maintain.

Example :

If Not DataReady() Then       '* precondition fails

Error 30005, "Data not available"

Else                                                   '* normal case

ProcessData

End If

·  Use proper spellings and punctuations in comments.

Rationale: Poorly written comments are distracting and can obscure the intended meaning.

 

2         Naming Conventions

2.1  Variable and Parameter Names

Variable and parameter names should be meaningful noun or noun phrases, without spaces, with the first letter lowercase and the first letter of any subsequent words capitalized.   The first few letters of the variable name define the type of the variable.  The remainder of the name describes the role the variable plays.

2.1.1       Constant Names

The names of constants should be meaningful noun or noun phrases with all letters  capitalized and underscore "_" between each word.

Rationale:   Consistency with standard Visual Basic and Windows API naming conventions.  This convention emphasizes and differentiates constants from variables.

Example : MAXIMUM_NUMBER_OF_FILES

2.1.2        Atomic Types

For atomic types, the first letter of the name defines the type, as follows:

Variable Subtype

Prefix

Example

Boolean use of variant variable

bln

blnEditBoxExists

Byte use of variant variable

byt

bytDownloadedData

Date or Time use of variant variable

dtm

dtmCreatedDate

Double use of variant variable

dbl

dblPiValue

Error use of variant variable

err

errLogin

Integer use of variant variable

int

intDuration

Long use of variant variable

lng

lngPopulation

Object use of variant variable

obj

objArtClass

Single use of variant variable

sng

sngGradePointAverage

String use of variant variable

str

strLastName

Variant

var

varGrade

 

Rationale: Consistency with standard Visual Basic and Windows API naming conventions.  This allows easy identification of the type and role of a variable, without adding a lot of naming overhead for frequently used types.

2.1.3        Object Name Conventions

For objects and complex types, and three-letter prefix defines the type, as follows:

Prefix

Type

Example

txt

TextBox

txtFirstName

chk

CheckBox

chkPrimaryAddress

tar

TextArea

tarComments

but

Button

butSave

rgp

RadioGroup

rgpSex

lnk

Link

lnkGetClient

Lst

Dropdown List

lstEmployeeStatus

bro

Browser

broAOSApp

ele

WebElement

elePolicyNumber

pge

Page

pgeAlert

Frm

Form

frmCustInput

lst

ListBox

lstServiceTypes

cmd

Command Button

cmdCancel

cbo

ComboBox

cboCategory

sel

Select (drop down)

selCategory

pic

PictureBox

picLogo

opt

Option Button

optGenderFemale

tmr

Timer

tmrElapsed

lbl

Label

lblCopyright

tbr

Toolbar

tbrEditing

ctl

Control (if type is not known)

ctlSortableList

col

Collection

colFormFields

obj

Object (if type is not known)

objParent

var

Variant (if type is not known)

varNextField

img

Image

imgIcon

Fra

Frame

fraLanguage

Many other types are possible which are not on this list, including user-defined types and objects. For these types, and appropriate three-letter or four-letter prefix convention should be established and documented for the project.

(Note that the "frm" prefix should be used only for a variable in the code which holds a form reference, and not the VB class and file which defines the form.)

Rationale: Consistency with standard Visual Basic and Windows API naming conventions.  Allows easy identification of the type and role of a variable.

2.1.4        Global Variable Names

Names for global variables should follow the above conventions, but with a "g_" prefix before the name.   Likewise, private module-level variables should have a "m_" before the name.

Rationale: This eases identification of global and module-level variables.  While this convention is somewhat cumbersome, it appropriately discourages use of global variables and module-level variables.

Example:

Public g_strCurrentUser As String

Private m_aintTroubleCodes As Integer

2.1.5       Variable Scope Prefixes

As script size grows, so does the value of being able to quickly differentiate the scope of the variables. A one-letter scope prefix preceding the type prefix, separated by an underscore, provides this, without unduly increasing the size of variable names.

Scope

Prefix

Where Variable Is Declared

Example

Procedure-level

None

Event, Function, or Sub procedure.

intDuration

Script-level

s

HEAD section of an HTML page, outside any procedure.

s_blnEditBoxExists

Global-level

g

-

g_strValue

 

2.2  Array Names

Array names should begin with a lower case "a", followed by the prefix which describes the type of the array members, as described above, and followed finally be the descriptive name of the variable.

Note that Variants must often be used to hold arrays when they are passed as return values from functions.   In this case, the Variant should be named according to the array naming convention.

Rationale:   This identifies the variable as an array, and indicates its contents as well.

Example :

Dim astrUserNames(10)

Dim asngVertices()

Dim avarWords
avarWords = Split(strLine, strTab)

2.3  Procedures

A procedure is a grouping of code statements that can be called by an associated name to accomplish a specific task or purpose in a program.

There are 2 types of procedures, sub-routines and functions. A sub-routine is a block of code that can be called from anywhere in the script to accomplish a specific task and it does not return any value. A function is the same as a sub-routine but does return a value.

The syntax for both will be the same.    

Syntax

[SOURCE]+"_"+[PerformedAction]+[Parameterlist]

[SOURCE] is an abbreviation of the library/script name it is implemented at.

[PerformedAction] consists of two words, an action (verb) and an object the action is

performed against.

[Parameterlist] is a sequence of placeholders the function is fed with.

[ReturnValue] is the value returned by the function       

 

Examples:

If EditBox.vbs is the name of the library which implements a set of functions to access the EditBox Control, the naming convention followed by the functions/subroutines in the library is

EB_SetTextValue (strEditBoxObjectName, strValue)

EB_VerifyTextValue (strEditBoxObjectName, strValue)

2.4  Scripts

A QTP Test script is a folder containing the script file with the VBScript code and the corresponding initialization or configuration files required by QTP to load and execute the test. A test script can have a set of actions and collection of datasheets associated with actions. The artifacts which require the naming convention are the test script, action and the data sheets

2.4.1        Test Script

Syntax:

[FEATURE] + "_" + [FUNCTION] + "_" + {optional}

[FEATURE] is an abbreviation of the feature/module[in caps] it is intended to test

[FUNCTION] is the name of the function/sub module[in caps] it is intended to test

{optional} means that the remaining characters preceded by an underscore will be optional and left to each person to define a sensible name which clearly identifies each of the test scripts.

Example:

  The scripts testing a mailing application would use  the following naming conventions[the        naming convention depends on the way the test cases are classified and automated]

MAIL_INBOX_OPENMAIL

MAIL_INBOX_REPLYMAIL

MAIL_COMPOSE_SENDMAIL

2.4.2        Actions

If a script has only one action the name of the action should be the same as the script. If the script has multiple actions, the naming convention for the action should be similar to that of script, [FEATURE] + "_" + [FUNCTION] + "_" + {optional}

2.4.3        Datasheets

The datasheets associated with the script inherit the name from the action unless explicitly created and imported at run time. The naming convention defined below is for the external sheets which are saved in Excel sheets or tab separated txt files and imported by the script at runtime.

The external datasheets can be classified into 3 categories based on its usage

Input Files – The data stored in these files is used exclusively as input for the test case

Output Files - The data stored in these files is saved by the test script/action for further                   operations. ex. Output of an operation saved to file for verification.

Input/Output Files - The data stored in these files is used as input for the test case and some                           of the fields are updated at runtime

Temp Files – The datasheets created and used temporarily to save and use the data at run                           time.

The datasheets should be placed under appropriate directory based on usage.

Example:

       A input data sheet should be placed under

         <root>/datasheets/output/<name of script using datasheet>/<filename>

       Similarly, an output datasheet should be placed under

         <root>/datasheets/output/<name of script using datasheet>/<filename>

2.5  Libraries

Common used functions are placed in libraries.

Syntax:

       [Companyname]+[ShortName]+"vbsl"

Examples:

Companyname UltraGrid.vbs

Companyname WinEditor.vbs

CompanynameEditbox.vbs

 

 

3         Recommendations

This document provides suggestions and guidelines for improving the performance and reliability of your application.

3.1  Declarations

The following conventions help you build good abstractions that maximize cohesion:

·         Use narrow scoping.   Use private variables and constants whenever feasible.  Local (procedure-level) variables are preferred, followed by module-level, with global as a last resort.

Rationale: Increases cohesion.

·         Declare scope explicitly.   Use Private and Public, instead of Dim, for variables declared outside of procedures.

Rationale: VB has different defaults for each type of code module (form, class, etc.).  Explicitly declaring the scope of variables reduces confusion.

·         Declare variables and constants at the beginning of their applicable scoping construct (module or procedure).   VBScript allows you to declare variables anywhere within a module or procedure, but they should be placed at the top.

Rationale: This makes declarations easy to view, and avoids cluttering up the flow of executable code.  Usually the rationale for putting the declarations in the middle of the executable code is that it declares variables near the point where they are used.   But this is only important if procedures are allowed to grow beyond a manageable size.  If a block of code is independent enough to require its own variables, it belongs in a separate procedure.

·         Use narrow typing for objects.   Don't use an Object type when the true type of the object is known.  For example, if a variable contains a reference to a TextBox, the variable should be declared As TextBox, not As Object or As Control

Rationale: Narrow typing makes the true purpose of the variable more obvious.  It also allows VB to catch type mismatch errors at compile time, and execute more quickly at run time through early binding.

3.2   Explicitly destroy all objects and close all connections

Destroying objects and closing connections ensures resources are returned to the system. Objects and connections should be closed and destroyed in the opposite order in which they were created. Wait to create objects and open connections until immediately before they're needed. Likewise, destroy objects and close connections immediately after you're through with them.

Example:

Set objFso = Server.CreateObject("Scripting.FileSystemObject")

set f = objFSO.OpenTextFile…

f.Close

set f = Nothing

set objRS = Nothing

set objConn = Nothing

set objFso = Nothing

3.3   Use Option Explicit

Use Option Explicit.  Option Explicit should be included at the beginning of each module to enforce explicit declarations for all variables.   In the VB environment, the option to "Require Variable Declaration" should be set.  This tells VB to include Option Explicit in all new modules.

Rationale: When variables can be instantiated on the fly, typographical errors in variable names are not caught by the compiler and can cause run-time errors.

3.4   Use Local Variables in Subroutines and Functions

Local variables are those declared within subroutines and functions. Within a function or subroutine, local variable access is faster than global variable access. Use of local variables also tends to make code cleaner, so use them when you can.

3.5   Avoid Redimensioning Arrays

Try to avoid Redim arrays. As far as performance is concerned, if you have a machine that is constrained by physical memory size, it's much better to set the initial dimension of the array to its worst-case scenario—or to set the dimension to its optimal case and Redim as necessary. This does not mean that you should just go out and allocate a couple of megabytes of memory if you know you aren't going to need it.

   The code below shows you gratuitous use of Dim and Redim.

Dim MyArray ()

Redim MyArray (2)

MyArray (0) = "hello"

MyArray (1) = "good-bye"

MyArray (2) = "farewell"

...

'Some other code where you end up needing more space happens, then ...

Redim Preserve MyArray (5)

MyArray (3) = "more stuff"

MyArray (4) = "even more stuff"

MyArray (5) = "yet more stuff"

It is far better to simply Dim the array to the correct size initially (in this case, that's 5), than Redim the array to make it larger. You may waste a little memory (if you don't end up using all of the elements), but the gain will be speed.

3.6   Use a Shared Object Repository

Always use a shared object repository for easier maintenance. Recommended practice is to record all the controls of the application at one go and save the object repository.

Click the Test / Settings menu item to select the shared object repository for the script.

         

3.7   Save Global/Environment variables in a file

Always define the environment/global variables used across different scripts/actions in an ".ini" file and load the file into the test script instead of directly adding them to the script settings. It is easy to maintain the variables defined in a file and can be reused across different scripts by loading the file instead of redefining the variables.

           

3.8   Avoid Usage of Hard Coded Paths

Always use relative paths in specifying the location of a file or action included in the test script. This makes the test scripts portable. The items which are prone to be hard coded are call to external action, Associated Library files, shared Object repository, Environment variables file.

Example:

Assume the test scripts are present in the following location D:\Temp\TestScripts folder and TestScripts is parent folder under which all the automation scripts are saved.

Then, All the paths should be mentioned relative to TestScripts folder. The path D:\Temp\TestScripts should be added in the Tools/Options window, Folders Tab for QTP to identify the parent folder.