Sunteți pe pagina 1din 106

2 Copyright Notice

Copyright Notice
TestComplete, as described in this help system, is licensed under the software license agreement distributed
with the product. The software may be used or copied only in accordance with the terms of its license.

TestComplete is Copyright © 1999-2009 AutomatedQA Corp. ALL RIGHTS RESERVED.

No part of this help can be reproduced, stored in any retrieval system, copied or modified, transmitted in any
form or by any means electronic or mechanical, including photocopying and recording for purposes others than
personal purchaser's use.
All AutomatedQA product names are trademarks or registered trademarks of AutomatedQA Corporation. All
other trademarks, service marks and trade names mentioned in this Help system or elsewhere in the
TestComplete software package are the property of their respective owners.
TestComplete includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit
(http://www.openssl.org). This software is copyright © 1998-2005 the OpenSSL Project. It is provided by the
OpenSSL Project “as is” and any expressed or implied warranties including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the
OpenSSL Project or its contributors be liable for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of substitute goods or services, loss of use,
data, or profits; or business interruption) however caused and on any theory of liability, whether in contract,
strict liability, or tort (including negligence or otherwise) apprising in any way out of the use of this software,
even if advised of the possibility of such damage.
TestComplete includes the UnzDll.dll library that is supplied by Info-Zip. This library is copyright ©
1990-2005 Info-ZIP. This software is provided “as is”, without warranty of any kind, expressed or implied. In
no event shall Info-ZIP or its contributors be held liable for any direct, indirect, incidental, special or
consequential damages arising from the use of or inability to use this software.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Table of Contents 3

Table of Contents
INTRODUCTION ............................................................................................................................................4
Introducing TestComplete ..............................................................................................................................4
Difference Between Standard and Enterprise Editions...................................................................................4
System Requirements .....................................................................................................................................6
Supported Development Tools .......................................................................................................................8
Technical Support and Resources...................................................................................................................9
GETTING STARTED....................................................................................................................................11
TestComplete – Product Overview...............................................................................................................11
User Interface – Overview........................................................................................................................11
About Projects and Project Items .............................................................................................................13
TestComplete User Interface and Object Browser ...................................................................................15
TestComplete’s Test Log ..........................................................................................................................16
Stores and Checkpoints ............................................................................................................................18
Looking Inside Applications .....................................................................................................................19
Testing Through Application Code...........................................................................................................20
Creating a Project .........................................................................................................................................21
Defining Applications to Test.......................................................................................................................25
Exploring the Application in the Object Browser ........................................................................................29
Creating Tests ...............................................................................................................................................36
Recording a Test Script ................................................................................................................................38
Analyzing the Recorded Script.....................................................................................................................45
Editing and Writing Scripts ..........................................................................................................................58
Specifying Execution Order for Tests ..........................................................................................................63
Running the Created Tests............................................................................................................................67
Analyzing Test Results .................................................................................................................................70
Searching for the Reason of an Error ...........................................................................................................72
SCRIPTING....................................................................................................................................................74
Writing Scripts – Overview ..........................................................................................................................74
Selecting the Scripting Language .................................................................................................................76
Writing Scripts – Quick Start .......................................................................................................................77
How TestComplete Recognizes Processes, Windows and Controls ............................................................88
Calling Routines and Variables Declared in Another Unit...........................................................................96
Supported Scripting Languages – Peculiarities of Usage .............................................................................98
INDEX ...........................................................................................................................................................105

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


4 Introduction

Introduction

Introducing TestComplete
TestComplete is an automated testing environment for Win32, .NET and WPF applications. It provides
extended support for testing Web pages, Web servers and projects created in Microsoft Visual C++, Visual
Basic, Borland Delphi, C++Builder, Java, .NET and WPF development tools.
TestComplete manages scripts to test applications externally, self-testing by the applications themselves, and
many inside-outside forms of tests. It is oriented equally to unit testing and to functional testing, provides
superior support for daily regression testing and supports many other kind of testing (data-driven testing,
object-driven testing, etc.)
If you are new to TestComplete, see Getting Started to learn how to use the product.
To get to know basic concepts, please read TestComplete - Product Overview (this topic is part of the Getting
Started section).

A note about plug-ins: TestComplete’s entire architecture is COM-based. Most of the features you see in the
product are supported through plug-ins. When the plug-in is meant to remain for the life of the current version,
it is made an internal part of TestComplete.exe. When it is possible that the plug-in could be updated, it is left
external (such as the database-access plug-ins). Others will be added to the AutomatedQA Web site
(http://www.automatedqa.com), and users can write their own plug-ins using the supplied interface
documentation and libraries – several user-contributed plug-ins are in
http://www.automatedqa.com/downloads/plugins.asp.
In fact, there are so many “open” features to TestComplete that we have put a checklist into a separate topic,
Open Access.

Difference Between Standard and Enterprise Editions


There are two editions of TestComplete: Standard and Enterprise. The following matrices explain differences
between them.

Features Supported by Both Standard and Enterprise Editions


Features Standard Edition Enterprise Edition
Black-box testing + +
(functional testing of any Windows application)

Extended support for .NET applications + +

www.automatedqa.com TestComplete by AutomatedQA Corporation


Difference Between Standard and Enterprise Editions 5

Extended support for Microsoft Visual C++ applications + +


Extended support for Microsoft Visual Basic applications + +
Extended support for Java applications + +
Extended support for Borland Delphi applications + +
Extended support for Borland C++Builder applications + +
Support for 64-bit applications + +
Extended support for applications using Microsoft Active + +
Accessibility (Microsoft Visual FoxPro, Microsoft Access,
etc.)
UI Automation technology support + +
Extended support for WPF (XAML) applications + +
Extended AQtime integration and coverage testing + +
Testing applications running under another user account + +
Support for third-party grid controls + +
Support for third-party menus + +
Scripting and script debugging + +
Event handling + +
Unit testing + +
(including support for MSTest, JUnit, NUnit and DUnit unit
tests)
Functional testing (or user interface testing) + +
ActiveX objects support + +
Low-level recording and playback + +
Name mapping + +
Object-driven testing + +
Data-driven testing + +
Source code control integration + +
User forms + +
Calling functions located in .NET assemblies + +
Calling functions located in DLLs + +
ADO and BDE support + +
CORBA support + +

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


6 Introduction

Compression of test results + +

Features Available in the Enterprise Edition Only


Features Standard Edition Enterprise Edition
HTTP load testing - +
Network suite (distributed testing) - +
Functional testing of web pages (web testing) - +
Testing of web services - +
Optical character recognition - +
Microsoft Visual Studio and Team System integration - +

Issue-tracking support - +
TestExecute - +
TestRecorder - +
TestComplete Enterprise Edition includes special plug-ins that allow you to simulate virtual users and perform
the load, stress and scalability testing of your Web servers. The basic TestComplete Enterprise license supports
only 5 virtual users. You can purchase versions that support more virtual users. For detailed information,
please visit AutomatedQA's web site:
¾ http://www.automatedqa.com/products/testcomplete/tc_matrix.asp

System Requirements
Supported Operating Systems
• Microsoft Windows Vista (both 32-bit and 64-bit editions).
• Microsoft Windows Server 2008 (both 32-bit and 64-bit editions).
• Microsoft Windows XP (both 32-bit and 64-bit editions).
• Microsoft Windows Server 2003 (both 32-bit and 64-bit editions).
• Microsoft Windows 2000.
• Microsoft Windows NT with Service Pack 6 or later.
• Microsoft Windows ME.
• Microsoft Windows 98.

If you use a computer that has several processors or a multiple-core processor (for example,
dual-core CPU) and has Windows XP Service Pack 2, then you must install the Windows
update #896256 in order for TestComplete to be able to record user actions correctly. The

www.automatedqa.com TestComplete by AutomatedQA Corporation


System Requirements 7

update is available on Microsoft’s web site:


http://support.microsoft.com/kb/896256

In order to install TestComplete, you must be logged on under the administrator account on the local
computer. To register TestComplete, administrator permissions are not required.
For information on using TestComplete and the Windows Firewall, see TestComplete and Windows
Firewall in TestComplete help.
For more information on working under Windows Vista and Windows Server 2008, see Testing
Applications With TestComplete Under Windows Vista and Windows Server 2008 in TestComplete
help.

Minimal System Requirements


• Intel Pentium II 400 MHz or higher.
• Microsoft Windows 98 or later.
If you use Windows XP Service Pack 2 on a computer with several processors or a multiple-core
processor, you must install Windows update #896256 in order for TestComplete to record user
actions correctly. The update is available at http://support.microsoft.com/kb/896256.
• Microsoft Internet Explorer 5.0 or later.
• 256 MB of RAM.
• 460 MB hard disk space.
• VGA (640 × 480) or higher resolution monitor.
• Mouse or other pointing device.

Recommended System Requirements


• Intel Pentium 4 3 GHz, Intel Core 2 Duo 2 GHz or higher.
• Microsoft Windows XP or later. Also, it is recommended that you install the latest service packs
and updates for your operating system.
Note again, that if you work under Windows XP Service Pack 2 on a computer with several
processors or a multiple-core processor, you must install Windows update #896256 in order for
TestComplete to record user actions correctly. The update is available at
http://support.microsoft.com/kb/896256.
• Microsoft Internet Explorer 6.0 or later.
• 1 GB of RAM on Windows XP and Windows Server 2003.
2 GB of RAM on Windows Vista and Windows Server 2008.
• 500 MB hard disk space.
• SXGA (1280 × 1024) or higher resolution monitor.
• Mouse or other pointing device.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


8 Introduction

Additional Requirements
• To test Java Open Applications, you must have one of the following Java virtual machines
installed on your computer:
ƒ Sun JDK (or JRE) v. 1.1.8 - 1.6.
ƒ MSVM, build 3309 or later.
ƒ BEA JRockit 5.0.
• To test .NET Open Applications, the Microsoft .NET Framework v. 1.0.3705 or later is required.
• To execute TestComplete tests from test projects created in Microsoft Visual Studio 2005,
Microsoft Visual Studio 2005 Team Suite ver. 8.0.50727.42 or later or Microsoft Visual Studio
2005 Team Edition for Software Testers ver. 8.0.50727.42 or later are required.
• To install TestComplete’s Microsoft Visual Studio 2005 Team Foundation Integration package,
Microsoft Visual Studio 2005 Team Foundation Server Release is required.
• To perform load testing of Web servers, Microsoft Windows 2000, Window XP, Windows Server
2003 or Windows NT with Service Pack 6.0 or later is required. Also, it is recommended that your
computer meets the following requirements:
ƒ Minimal Configuration
- Intel Pentium III 800 MHz.
- 256 MB of RAM (for 300 virtual users).
ƒ Recommended Configuration
- Intel Pentium 4 3 GHz with HyperThreading, Intel Core 2 Duo 2 GHz or higher.
- 1 GB of RAM (2 GB on Windows Vista and Windows Server 2008).
To install and run load testing samples, Microsoft Internet Information Services 5.0 or later are
required. Also, to run load testing samples under Windows Vista, you should modify some of the
IIS settings. For more information on this, see Running Load Testing Samples Under Windows
Vista in TestComplete help.

Supported Development Tools


“Will TestComplete test my application?” - This is probably one of the first questions our clients ask about
TestComplete. As a matter of fact, TestComplete does not depend on any development tool. It can simulate
user actions (keypresses, mouse movements and clicks) under any application no matter whether this
application was created in C#, Visual C++, Delphi or Java. However, in most cases, this kind of testing (testing
via GUI) cannot provide reliable and thorough results. Quite often, QA engineers need access to the
application internal objects, methods and properties. This is required, for example, for unit testing. You can get
this access using TestComplete. It “opens” the internal objects, methods and properties up to private object
elements in applications that were created with the following development tools:
All existing .NET compilers. For instance:

www.automatedqa.com TestComplete by AutomatedQA Corporation


Technical Support and Resources 9

Microsoft: Visual C#, Visual Basic .NET and Visual C++ .NET v. 7.0 and later (managed
code) (Visual Studio v. 8.0 only with Service Pack 1 installed), JScript .NET
Non-Microsoft: Borland C#Builder, Borland Delphi for .NET (Delphi 8 and Delphi 2005),
Python .NET, Cobol .NET, Perl .NET, etc.
Microsoft Visual C++ 6.0, Visual C++ 7.0 and later (unmanaged code) (Visual Studio v. 8.0 only
with Service Pack 1 installed).

64-bit .NET, Java and Windows applications (see Testing 64-bit Applications in TestComplete
help).

Microsoft Visual Basic 6.0

Borland Delphi 3.0 and later (including CodeGear Delphi 2007)

Borland C++Builder 3.0 and later

Any Java development tool that supports one of the following Java virtual machines:
ƒ Sun JDK (or JRE) v. 1.1.8 - 1.6. TestComplete also supports 64-bit JRE 1.6 applications.
ƒ MSVM, build 3309 or later
ƒ BEA JRockit 5.0
For instance, you can use Microsoft Visual J++ 1.1, Borland JBuilder 3.0, Sun Forte 1.0 and other
development tools. The AWT, SWT, Swing and WFC library classes are also supported.

Sybase PowerBuilder 10.0 and later

Microsoft FoxPro 7.0 and later

Microsoft Office Access 2003 and later

Microsoft Office InfoPath 2003 and later


Since TestComplete can test any Windows application via GUI, it can simulate keypresses and mouse clicks in
any Internet browser. This allows you to test Web pages working with any Internet browser. However,
currently, you can only access properties and methods of HTML elements on a Web page shown in Internet
Explorer, Firefox or in any instance of the Web Browser control. See Web Testing in TestComplete help for
complete information on this.
As for the performance, load, stress and scalability testing of Web servers, they do not depend on Internet
browsers (Internet Explorer, Netscape Navigator, Mozilla, Opera, etc.), the server type (Microsoft IIS, Apache,
etc.) or platform (Windows, Linux, etc.) That is, with TestComplete you can perform these kinds of testing for
any Web server working on any platform. Please see Load, Stress and Scalability Testing of Web Servers With
TestComplete in TestComplete help.

Technical Support and Resources


If you have questions, problems or just need help with TestComplete, contact our support team. To submit
your question, please use the Contact Support Form at:

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


10 Introduction

¾ http://www.automatedqa.com/support/message.asp
The support team will answer you via e-mail and all further communication will be made via e-mail. However,
to start the conversation, please use the Contact Support Form.
For information on our support policies, please visit our web site http://www.automatedqa.com/support.

You can also ask questions, search for answers, exchange comments and suggestions on our newsgroup and
on the Community web site:

¾ forums.automatedqa.com.public.testcomplete
¾ http://www.automatedqa.com/community

You can find answers to your question in the list of the frequently asked questions which is available at:

¾ http://www.automatedqa.com/products/testcomplete/faqs/tc_faqs.asp

Take part in TestComplete training seminars offered by AutomatedQA. To learn more about training
services, please follow this link:

¾ http://www.automatedqa.com/support/training.asp

Learn more about using TestComplete from technical papers published at:

¾ http://www.automatedqa.com/techpapers/

Make sure you regularly visit the AutomatedQA Web site, http://www.automatedqa.com, where you will
find -
• News
• Updated support options
• Downloads, such as plug-ins and free tools
• Hot Stuff contributed by experienced users and the AQA team (hands-on solutions, code, plug-ins,
etc.)

www.automatedqa.com TestComplete by AutomatedQA Corporation


TestComplete – Product Overview 11

Getting Started

TestComplete – Product Overview

User Interface – Overview


The user interface of TestComplete consists of panels, the main menu and toolbars. The general layout is as
follows:

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


12 Getting Started

Most of TestComplete’s screen area is occupied by panels. Panels are where you do your actual work and get
your results. Each panel serves a separate purpose for your work in TestComplete. There are three “main”
panels:
Panel Description
Project Explorer Displays the contents of the project suite, its projects and project items.
Workspace This panel is your work space in TestComplete. It holds a set of tabbed pages, in
which you can modify properties of project items. When you double-click an item in
the Project Explorer, TestComplete opens the appropriate tab page in the Workspace
panel.
Object Browser TestComplete "sees" a lot of the applications under test, as well as all applications
running on the machine. The Browser shows all of this in a navigational tree format.
Everything that can be found in the Browser can be used in a test - the Browser is your
test-object map, using the universal TestComplete object model. Names and values
can be copied from the Browser and pasted to scripts. Values of all kinds can be saved
from the Browser to Stores for later comparison.
There are more panels that are used for editing and debugging script code:
Panel Description
Bookmarks Shows a list of bookmarks set in the script code. Used for script editing.
Search/Replace Displays results of the search or replacement operations.
Results
Watch List Used for script debugging. Shows variable and property values during test runs.
Call Stack Used for script debugging. During script execution, it shows the stack of function calls that
led to the execution of the current routine.
Breakpoints Displays information about breakpoints. Used for script debugging.
Locals Displays information about the available script variables that are used for script
debugging.
Code Explorer Navigates through scripts that are kept within the project. Used for script editing and
debugging.
The size and layout of panels is not fixed. You can change panel sizes by dragging the separator between them.
However, the most important point about handling panels is how they can be moved around - docking.
Docking is our way of providing you with the most flexible workspace for the particular task you are interested
in. It means that the entire work area can be reconfigured as needed, even beyond what is possible with toolbars
(moving, hiding, etc.). Docking of panels in TestComplete is similar to docking windows in Microsoft Visual
Studio .NET. For more information, see Docking in TestComplete help.
There are some common ways of arranging columns and lines in the grids, which most panels display. For
instance, you can change the columns’ width, add or hide certain columns, sort data on a column by clicking
the column’s header and perform other operations. See Arranging Columns, Lines and Panels in
TestComplete’s help for more information.
Each panel has a number of options that you can modify in the Options dialog. To display the dialog, select
Tools | Options from TestComplete’s main menu. General settings of the panels can be changed in the User

www.automatedqa.com TestComplete by AutomatedQA Corporation


TestComplete – Product Overview 13

Interface dialog. To display it, choose Tools | Options from TestComplete’s main menu and then select
General | User Inerface in the ensuing Options dialog.
To save the current panel layout to a file, select View | Desktop | Save Docking to File from TestComplete’s
main menu (by default, these files have the .qtdock extension). To load the panel layout from a file, select View
| Desktop | Load Docking from File. To restore the default panel layout, select View | Desktop | Restore
Default Docking. The Save Desktop As and Load Desktop items of the View | Desktop submenu will save
and load the panel layout along with the toolbar settings.
TestComplete's interface receives commands in four ways:
• Through menus.
• Through popup menus (right-click, context-dependent).
• Through toolbars.
• Through keyboard shortcuts.
Keyboard shortcuts are especially useful during recording, since they let you command TestComplete without
moving the focus off the tested application. These shortcuts can be customized with the Global Shortcut
Options dialog.
As in Microsoft Word or Excel, menus are a type of toolbar, and both can be customized as needed. You can
also create your own toolbars. By default, toolbars are docked at the top of the TestComplete window. You can
easily dock them to any other edge by dragging them to the left, right or bottom edge of the window. To
remove or add buttons, you can either call the Toolbar Customization window or use the Quick Customization
feature. See Toolbars Customization in TestComplete help for more information.
To save or load the current layout of toolbars and toolbar items, use the View | Toolbars | Save Toolbars to
File and View | Toolbars | Load Toolbars from File menu items. To restore the default toolbar layout, select
View | Toolbars | Restore Default Toolbars. To save and load the layout of panels, menus and toolbars, use
the View | Desktop | Save Desktop As and View | Desktop | Load Desktop menu items.

About Projects and Project Items

Projects and Project Suites


Similar to program development tools, such as Microsoft Visual Studio or Borland Delphi, the primary unit of
management in TestComplete is a project. A project contains data and files (project items) that are needed to
perform tests as well as a cumulative log of all test runs since the start of the project.
Related projects can be united into a project suite that contains one or more projects. TestComplete
automatically generates a project suite when you create a new project. You can also create empty project suites
and then use TestComplete’s dialogs to fill the suite with the desired project files.

Project Items
Project items are elements that perform various testing operations or assist in performing these operations.
Each project item is a collection of child items and files. By default, the child items are stored in files located in
subfolders of the project’s folder.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


14 Getting Started

The Project Explorer panel provides a graphical interface to view and manage the projects, project suites and
project items:

For complete information on project items available in TestComplete, see About Project Items in
TestComplete help.
To view or modify properties of a project item or properties of its child element, right-click the desired item or
element in the Project Explorer panel and choose Edit from the context menu, or simply double-click the item
(or element). TestComplete will show the property editor in the Workspace panel:

www.automatedqa.com TestComplete by AutomatedQA Corporation


TestComplete – Product Overview 15

In addition to the editor displayed in the Workspace panel, TestComplete offers other helper panels and
windows for some project items to make editing more convenient. For instance, TestComplete includes the
Code Explorer panel which makes it easier to navigate through script units.

About Test Items


Most project items can be used to perform testing actions. For instance, Script and Low-Level Procedures can
simulate user actions; HTTP Load Testing can simulate the user activity over a Web server, and so forth. In
other words, a project item can be used as a source of the entire test or a part of the test (we call these parts test
items). The sequence of test items to be run is specified in the Test Items page of the project editor. A project
itself can be used as a test item when you create tests for project suites. For more information, read Creating
Tests.

TestComplete User Interface and Object Browser


TestComplete’s desktop is organized into a number of panels (see User Interface – Overview):

The Project Explorer panel displays a tree of project items, their child elements and test log nodes. The
Workspace displays editors for the selected project item as well as test log pages.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


16 Getting Started

The Object Browser panel holds one major TestComplete function that does not belong to a specific project.
The Object Browser maps all processes currently running on the machine, whether they are an application for
testing, a basic operating system service like the Explorer process, or some other application like Internet
Explorer or TestComplete itself. For each process it shows all objects accessible externally through
TestComplete facilities, and all of the accessible object properties and methods. It also shows the simulated
user actions possible on the object; these are simply called actions.
In other words, the Browser tells you everything that is available for external testing, and how to get to it. It
also lets you take screen clips (by window objects or by rectangle) and store them as images with the current
project. It does the same for any collection of object properties you may wish to store. Finally, there are several
ways of copying information from the Browser to the clipboard, or directly into scripts.
The fastest way to understand how TestComplete supports external testing is to spend some time in the Object
Browser. See Exploring Application Properties in TestComplete help.

TestComplete’s Test Log


Each project holds a log of all project runs. In fact, the best definition of a project is “what TestComplete
maintains a log for”. Everything else is secondary. The log is where you get the results of the entire testing
exercise.
The basic unit of the log is a test. The log itself is an object that can be called in scripts or code. Using
TestComplete in the simplest way, you launch a test by right-clicking a project or project item in the Project
Explorer panel and selecting Run from the context menu. The log is smart enough to know that the current test
starts when the project item’s execution begins, and ends when the execution stops. A project item (for
example, script) can call other project items or run applications that access the Log object - the “current test”
goes on until the execution of the “parent” item is finished. The only thing you cannot do is run several tests on
the same computer in parallel.

www.automatedqa.com TestComplete by AutomatedQA Corporation


TestComplete – Product Overview 17

For each test, the log records start, stop, duration and completion (non-completion means the test could not
continue to the end).

The log has a tree-like structure similar to the structure of the executed test items. Each node in this tree has a
specific format of results. This format depends on the project item, in which a test item is based. For instance,
the log of a script execution is a tree-like structure of messages of various kinds. TestComplete supports a large
variety of ways to differentiate these messages:
• It automatically logs the exact message time, so you can get the time spent between any two
messages.
• Each message is posted according to one of the following message types - Error, Warning, Picture,
File, Link, Event and the ordinary Message (called information message in the Help to
differentiate it from other messages).
• Each message also has a priority level.
• Messages contain text and additional comments (or remarks). Each message can also have an
image associated with it.
• Related messages can be organized into folders within the log.
• Finally, filters can be defined to create reports of any type.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


18 Getting Started

If your script or other test code does not post messages to the log, the only messages you will find are possible
error messages from TestComplete itself. Therefore, unless you are simply trying out a test, the one thing it
must do is post messages. This cannot be recorded, you have to write script code for it.

Stores and Checkpoints


A typical test performs a lot of comparisons. Comparisons are the core of regression testing. One regression
test can involve thousands of comparisons. Other forms of testing also need a validated reference during
automation.
To support the comparison, you can add the Stores project item to your test project. This project item contains
various elements that are saved along with the project for comparison purposes. We call the comparison or
verifying operations checkpoints. The Stores project item contains elements that are used to create
checkpoints.
The elements are organized into a number of collections. Currently, the item includes the following
collections:
• Regions - Contains elements used to compare images and find one image within another.
• Files - Contains elements used to compare files.
• Objects - Contains elements used to compare properties of an object or window.
• DBTables - Contains elements used to compare and verify data of a database table, view or query.
• Tables - Contains elements used to verify data of controls that display information in tabular form
as well as data of list view, list box and combo box controls.
• WebTesting - Contains elements used to verify web pages and compare them.
• XML - Contains elements used to compare XML documents and check web service responses.
Each Stores collection has a corresponding program object which contains methods that automatically perform
the comparison (or verification) operations and report the results. That is, to perform the comparison or
verification, you should call the appropriate method in scripts. For instance, to compare images, you call the
Compare method of the Regions object.

You can perform the operations needed for creating the comparison code manually, or you can create this code
by using TestComplete’s wizards and dialogs. Using the wizards and dialogs greatly simplifies the creation of
the comparison code (that is, they simplify the creation of checkpoints).

www.automatedqa.com TestComplete by AutomatedQA Corporation


TestComplete – Product Overview 19

You can create checkpoints at design time by selecting items of the Tools toolbar or you can create checkpoints
during test recording through the Add Checkpoints item of the Recording toolbar:

Upon selecting the menu item, TestComplete displays a dialog or wizard, in which you specify the checkpoint
parameters. After closing the dialog (or wizard), TestComplete generates the verifying script statements,
which you insert into your script code.
For more information on creating checkpoints and verification code, see About Checkpoints in TestComplete
help.

Looking Inside Applications


TestComplete’s Object Browser shows a lot of detail about applications running in the operating system and
their windows and controls. All of the displayed methods, properties and actions can be used in your tests.
By default, the processes and windows only contain methods and properties provided by TestComplete. You
can use them to test your application via the GUI, that is, to simulate keystrokes and mouse actions over
windows and controls and to check certain windows’ attributes (like style, text and visibility).
This may be enough to create simple tests, but quite often, testing routines need access to those methods and
properties that are provided by the tested application. In other words, they require access to the objects,
methods and properties provided by the programming libraries that were used to create the application
(WinForms, MFC, VCL, SWT, AWT and others).
If applications test themselves using their own code, then access to the applications’ internal objects is usually
not a problem. However, even if applications are tested externally (for instance, with TestComplete scripts),
there is no reason to use a simple GUI-test. Where possible, tested applications should be Open Applications,
that is, they should provide access to their internal objects, methods and properties.
.NET, Java, Visual Basic, WPF and Java applications are “opened” by special plug-ins. All you need is to
install these plug-ins in TestComplete. Visual C++, Delphi and C++Builder applications need to be recompiled
in a special way to become “Open”. Compiling the application as an Open Application is fairly simple.
Typically, it requires compiling the application with debug information and including one or two special units
in your Visual C++, Delphi or C++Builder project. TestComplete has an exclusive technology called Debug
Info Agent™ that works with tests to access practically all internal elements of the application under test, even
private properties. For detailed information on Open Applications and on creating them, see the Open
Applications topic in TestComplete help.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


20 Getting Started

Once your application is “open” look at it through the Object Browser. You will see that making the
application “Open” has multiplied the access to application objects for your test code. You can test much closer
to the design level, and much more conveniently. Depending on the level of “openness”, you can use public,
protected and even private methods, fields and properties in your tests.
TestComplete also includes two special plug-ins that provide deeper access to applications’ internals in
comparison to the default access. One of these plug-ins, UI Automation Support, retrieves window properties
provided by Microsoft UI Automation Framework. Another special plug-in, MSAA Open Applications,
exposes methods and properties of windows that implement the IAccessible interface. This lets you work with
windows of Sybase PowerBuilder, Microsoft Access and Visual FoxPro applications. You can see the objects,
methods and properties, exposed by these plug-ins, in the Object Browser panel.

Testing Through Application Code


TestComplete’s services are provided through an OLE server. The entire user interface is simply a client of this
server. By linking in just one file, an application can put itself in the place of the TestComplete user interface
and run the OLE server directly, for whatever purpose. We call this a Connected Application.
The most common thing a Connected Application will do is run tests in its own source code (see Self-Testing
Applications in TestComplete help). This is usually the easiest way to do unit tests (see Testing With
TestComplete in TestComplete help).
Connected Applications can also be used to run tests on other applications. This way of testing provides more
control over test conditions, since the TestComplete engine is commanded from source code rather than the
user interface. For instance, you might want to run a specific series of tests at a given time, and which tests are
to be run would depend on the conditions at that time. All of these can be done from a rather simple Connected
Application.
Also, using Connected Applications simplifies the test creation because it is convenient to write test code in
your normal programming language and use the preferred IDE for debugging.
Of course, application code in a Connected Application still has access to all of the objects a script uses. These
are all OLE objects, and the needed interface is in the file that you link to.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Creating a Project 21

The following figure explains the relations between TestComplete and other applications (Open, Connected
and General applications):

Creating a Project
Projects contain all of the information about one or more applications that you test as well as data, scripts, a
baseline copy of files and images and other information needed to perform the test. For a complex application
you may choose to devote a project to just one part of the application, and other projects to other parts
(normally, modules).
Note: We will illustrate each step of this Getting Started section with the Orders sample application,
which is installed in the <TestComplete>\Samples\Open Apps\OrdersDemo folder.
Please compile this application before you proceed with Getting Started.
If you have any problems compiling the application, you can use the compiled executable that
resides in the <TestComplete>\Samples\Open Apps\OrdersDemo folder.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


22 Getting Started

To create a new test project:


• Select File | New | New Project from TestComplete’s main menu. This will call the Create New
Project dialog where you can specify the project name, location, template, scripting language and
the name and location of the project suite.

• Enter Orders as the project name and OrdersSuite as the project suite name. TestComplete will
automatically generate the project path and display it in the Actual location field. Note that if the
path is too long, TestComplete will shorten it by replacing some part of it with ellipsis. To view the
complete path, move the mouse pointer over the Actual location field.
The project folder is used to store all information generated for or by the project -- scripts, results
log, stores, and so on. You can change the project’s folder in the Location box. In our example
we will keep the folder name unchanged.
• If you are have a project suite open in TestComplete, select the Create a new project suite check
box (we will add the Orders project to the new suite).
• Then specify the project language, say VBScript.
Note: TestComplete is equally oriented to VBScript, JScript, DelphiScript, C++Script
and C#Script, therefore it allows you to select the language you know. You will be
able to use all of TestComplete’s features regardless of the language you choose.
However, due to the fact that languages have different syntax and their script
instructions are executed by different scripting engines, there are some exceptions

www.automatedqa.com TestComplete by AutomatedQA Corporation


Creating a Project 23

(see Supported Scripting Languages - Peculiarities of Usage in TestComplete


help). For more information on choosing the language, see Selecting the Scripting
Language in TestComplete help.
We would like to also note that the scripting language does not depend on your
tested application’s programming language. For instance, you can use JScript to
test Visual C++ applications, or VBScript to test Delphi programs. There is one
recommendation: if you plan to create a Connected or Self-Testing Application,
you should select the language that matches the development tool that the
application was created in. For example, if you use Visual C++ or C++Builder,
you should select C++Script; if you use Visual Basic, select VBScript, and so
forth. This will make it easier to import recorded scripts to Connected and
Self-Testing Applications.
After specifying the project name, location and scripting language, you can specify the project template.
Project templates define which project items your project will contain. The set of project items determines
what testing actions a project can perform. For instance, using the Low-Level Procedures Collection project
item you will be able to run low-level procedures and using the Events project item you will be able to handle
events.
The template specifies which of the project items will be included in your project by default. You can modify
the set of enabled items using the Project Wizard that is shown after you click OK in the Create New Project
dialog. You can also add the desired items to your project at any time. For more information on this, see Adding
and Removing Project Items and Their Child Elements in TestComplete help.
• In the Create New Project dialog, select any template in the Templates box and click OK.
TestComplete will open the Project Wizard where you can modify the project items to be included
in the project.
• Select any template in the Templates box.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


24 Getting Started

• Click OK in the Create New Project dialog. TestComplete will open the Project Wizard where
you can modify the project items to be included in the project.

Now let’s select project items for our sample project. It will contain scripts, a list of tested applications and
stores:
• Uncheck all the items in the Project Items list except for the Script item (as for tested
applications, we will add them later to demonstrate how to add items to existing projects. Stores
will be added during the script recording). Note that the Events item can only be unchecked if the
Insert general events in new projects option is disabled. You can do this in the Events Options
dialog before creating the project (to display the dialog, choose Tools | Options from
TestComplete's main menu and then select Engines | Events in the ensuing Options dialog).
• Click Next to switch to the next page of the Project Wizard.
• Switch to the Script page. Here you can add one or more script units to your project. By default,
TestComplete creates one unit named Unit1. This is enough for our sample project and there is no
need to create more units.
• Press Finish in the Project Wizard. TestComplete will create a new project file, Orders.mds, with
the Unit1 script unit and display the project’s contents in the Project Explorer panel.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Defining Applications to Test 25

Defining Applications to Test


Each project may have a list of tested applications. This is a way for you to keep track of which applications
the project deals with and how they are configured for testing. It also allows TestComplete to launch all
applications in the list or only those applications that are enabled to be launched manually via the context
menu, or from a script. Of course, since projects are independent from one another, any application may be in
more than one project’s list.
To add a Win32 tested application to our project, we first need to add the Win32 Tested Applications project
item. To do this:
• Right-click the project node in the Project Explorer panel and select Add | New Item from the
context menu.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


26 Getting Started

This will call the Create Project Item dialog.

• In the dialog:
ƒ Select the Win32 Tested Applications item.
ƒ Keep the value displayed in the Location box unchanged (this value specifies the folder where
the .tcTAs file contains the tested application’s settings).
ƒ Press OK.
TestComplete will add the Win32 Tested Application project item, TestedApps, to your project
and show it in the Project Explorer panel.
Now we can add our sample application to the tested applications list:
• Right-click the TestedApps node in the Project Explorer panel.
• Choose Add | New Item from the context menu. The standard Open File dialog will appear.
• Locate Orders.exe using this dialog and then click Open.
The application executable and the source code are in the <TestComplete>\Samples\Open
Apps\OrdersDemo folder.
In this tutorial, we use the Orders application compiled with Visual C#. So, if you installed
TestComplete to the default location, the path to Orders.exe looks like this: C:\Program
Files\Automated QA\TestComplete 6\Samples\Open Apps\OrderDemo\C#\bin\Debug\Orders.exe.
Now, the sample application is in the list and we can specify command-line arguments for it:

www.automatedqa.com TestComplete by AutomatedQA Corporation


Defining Applications to Test 27

• Double-click the TestedApps | Orders node in the Project Explorer panel. TestComplete will
show the available settings in the TestedApps editor.

• Now we should select the application’s run mode. A tested application can be launched in several
modes: Simple, RunAs, Debug or Profile. The Simple mode is similar to launching the application
from Windows Explorer or the command line window. Using the RunAs mode you can launch the
application under a different user account than TestComplete is currently running under. Debug
mode is similar to Simple, but TestComplete will act as a debugger for the application and will
report information about events and errors that occur during the application run. Finally, Profile
mode is used to debug and profile the application with AQtime. For more information on these
modes, see Run Modes in TestComplete help.
For our sample application we will use Simple run mode. This mode is used by default for tested
applications. Look at the Run Mode column and make sure the Simple mode is selected:

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


28 Getting Started

• Now we will change the application’s command line. To do this, press the ellipsis button within
the Parameters column. This will call the Parameters dialog.
• Type -NOTOPENAPP or /NOTOPENAPP in the Command-line parameters edit box. We will
explain this command-line argument later (see Exploring the Application in the Object Browser).

Press OK to close the dialog.

• Save your changes by selecting File | Save from TestComplete’s main menu.
As you can see, all application parameters (command line, work folder and so on) can be set in one place.
As stated above, one purpose of the tested applications list is to provide you with a way to launch all
applications before you start recording a script. Of course, you can record the launch of an application, but that
is inefficient for a number of reasons: the manner of launching from a desktop is cumbersome and/or fragile (a
shortcut icon can be hidden), providing special parameters is impossible, and so forth.
It is easier and more adaptable to have all the launch specifications you may need in the list, and to uncheck
anything that is not needed for the current run (in the Launch column). Then you choose Run Selected or Run
All from the context menu and wait until the application’s main window appears on screen.
In the next steps we will explore which internal objects, methods and properties of the tested application are
available to TestComplete and then will record user actions over the application.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Exploring the Application in the Object Browser 29

Exploring the Application in the Object Browser


Before recording or running a script, you can explore what properties, fields, methods and events of your
application’s object TestComplete has access to. As the Introduction states, TestComplete can access almost
all application objects, methods and properties, even if they are not part of the application UI. The Object
Browser panel shows you exactly what is available to your scripts:

The tree view on the left contains a list of processes that are currently running in the operating system and their
windows. All processes are direct children of System (the Sys object in scripts), and windows are children of
the process that opened them. In TestComplete terms, processes and windows are objects, and this is how they
are represented in scripts (see How TestComplete Recognizes Process, Windows and Controls in TestComplete
help).
The right pane displays the selected object’s methods and properties that are available to scripts.
If you use Windows Vista or Windows Server 2008 and you do not see an existing process in the Object
Browser, most likely the process and TestComplete have different permissions. In order for TestComplete to

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


30 Getting Started

be able to test applications under Windows Vista and Windows Server 2008, it must have the same permissions
as the application. See Testing Applications With TestComplete Under Windows Vista and Windows Server
2008 in TestComplete help.
Now we can explore our sample application.
• To launch the application, right-click the application node (Orders) in the Project Explorer panel
and select Run from the context menu. The application node is a child node of the TestedApps
node.
Wait until the application’s main window appears:

• Find the application in the Object Browser tree view. If the tree contains too many processes, you
can filter it to only view the tested applications. To do this, click Show Tested Applications
Only on the Object Browser’s toolbar.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Exploring the Application in the Object Browser 31

• Expand the application node and look at its windows and their properties. The right pane displays
properties and methods that can be used in scripts (see the image below).
Note: The following image displays the properties, methods and objects of the Orders
application created in C#. The properties, methods, window class names and the
whole object structure that you see in the Object Browser on your computer may
differ from what is displayed in the image. The information you see depends on
the development tool, which you used to compile the tested application. For
instance, the objects’, methods’ and properties’ names as well as the object
structure of Visual C++ 6 applications differ from those of .NET applications.

Currently, the windows of the Orders application contain only TestComplete-defined properties, not those
defined in the application source. This may be enough to test the user interface of some Windows applications,
since TestComplete supports almost all standard Windows controls: list views, combo boxes, tree views, and
so on.
If you want to dig deeper into the application, you must compile it as an Open Application. In this case, objects,
methods and properties defined in the source code become available to TestComplete scripts. Open

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


32 Getting Started

Applications can be created in any supported compiler. For some compilers, there is more than one way to
create an Open Application. Each variant provides a different degree of openness. Please read Open
Applications in TestComplete help for more information.
The Orders application is already compiled as an Open Application. It provides maximum openness, that is, it
makes all public, published and protected elements (with some restrictions) accessible to TestComplete and
script routines. Currently, TestComplete does not have access to internal properties and methods of the Orders
application because we have specified the -NotOpenApp command-line argument for the application. Let’s
change the command line:
• Close the Orders application.
• Double-click the application node in the Project Explorer panel. TestComplete will show the list
of the tested applications in the Workspace panel.
• Press the ellipsis button within the Parameters column.
• In the resulting Parameters dialog, remove -NotOpenApp from the Command-line parameters
edit box. Press OK to close the dialog.

• Save the changes by selecting File | Save from TestComplete’s main menu (this menu item can be
disabled, if you accidentally selected a project item other than TestedApps in the Project
Explorer).

www.automatedqa.com TestComplete by AutomatedQA Corporation


Exploring the Application in the Object Browser 33

• Right-click the application’s node in the Project Explorer panel and choose Run from the context
menu. TestComplete will launch the Orders application and you will be able to explore the
application’s objects in the Object Browser:

The Object Browser now displays a special icon ( ) for the Orders process. The icon indicates that
TestComplete recognizes the Orders application as an Open Application.
The Object tree shows a list of internal application’s objects. The image above shows the objects of the Orders
application compiled with Microsoft Visual C#. These objects are addressed with the syntax
WinFormsObject("Object_Name"). WinFormsObject is the method that is used to address objects in
.NET applications that were created with Microsoft’s Windows Forms library. If you compile the Orders
application with another compiler, TestComplete will address the objects using another method: VBObject,
VCLObject, SwingObject, and so on.

If the TestComplete 3 Compatibility plug-in is installed, TestComplete emulates the functionality of the
previous versions of TestComplete and will address objects by their names: MainForm, ImageList1, and so
forth. Since version 4, TestComplete uses other principles for addressing objects than the previous versions

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


34 Getting Started

used. The image above demonstrates when the compatibility plug-in is not installed. In this topic and other
topics of the Getting Started section, we will assume that the compatibility plug-in is not installed.
The right portion of the Object Browser displays properties and methods of the object selected in the object
tree. The method and property lists include methods and properties defined in the application’s source code as
well as methods and properties introduced by TestComplete. Note that some methods and properties are
unavailable to TestComplete (see Object Properties, Fields and Methods That Are Unavailable to
TestComplete in TestComplete help). Also, protected and private properties are hidden from the panel by
default. For more information on this, see Access to Properties in TestComplete help.
Now, let’s change the caption of the application’s main form. To do this:
• Locate the form in the Objects tree.
• Switch to the right pane and finding the Caption property.

• Specify the new caption in the Caption property and confirm the change by pressing ENTER.
The form caption will be changed. You have literally changed Orders’ internal data, and the next screen update
reflects the new data.

Note: For Visual C++ applications this procedure cannot be executed from the Browser, since
Visual C++ applications do not have properties (they use fields and methods). In this case,
you can change the form’s title by calling the appropriate Visual C++ method.

Note that some methods and properties remain unavailable to TestComplete even if the application is compiled
as an Open Application. There are a number of reasons for this. Typically, it occurs with non-OLE-compatible
properties, with methods containing non-OLE-compatible parameters or return values. See Object Properties
Fields and Methods That Are Unavailable to TestComplete in TestComplete help for more information.
Some Read/Write properties are displayed as Read-Only ( ) or Write-Only ( ). These properties will be
Read-Only or Write-Only in scripts. Usually, this means that the property value is not read or set in the
application’s source code, that is, the application does not call the “get” or “set” function, so the compiler does
not include the function in the application’s binary code.

The following properties of Visual Basic applications are not accessible to interprocess
calls:
• Icon
• Image
• MouseIcon
• Palette
• Picture
As a result, if you try to view these properties via the Object Browser, an error will occur in
the Visual Basic application you are exploring.

One last feature of the Browser is that it lets you explore the internal structure of COM objects if you know
their class or program identifiers, for instance Word.Application or Scripting.FileSystemObject.
Try the following:
• In the tree view select the root node (Sys).

• Find the OleObject property in the right pane.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Exploring the Application in the Object Browser 35

• Click the Params button. This will call a small dialog.


• Assuming Word is installed on your machine (open or not), enter its program identifier,
Word.Application, in the dialog and press OK. (Note that you can use the class id as well as
the program id).

• Wait until the OleObject property displays IDispatch for a value. This means you supplied the
correct identifier and TestComplete successfully obtained a reference to the desired object
(IDispatch indicates that the value is an object).
The OleObject property acts as an indexed property that uses program (or class) identifiers as
parameters. Supply a valid index, and a valid value will be created for it (the IDispatch interface
that is now available).
• The new value (IDispatch), in turn, displays its own ellipsis button. Press it to explore the
desired COM object.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


36 Getting Started

Creating Tests
General Notes
Before you create a new test, you should plan it:
• Define the test goal (decide which application functionality to be tested).
The clearer the goal and the simpler the test, the better. Do not create tests that will test various
aspects of the application’s behavior at one run. It is better to create a simple test that is aimed at
one objective only. Such tests are easier to create and maintain. Once you create several simple
tests, you can always organize them into a larger test.
• Plan testing steps (decide which actions the test will perform).
The testing steps depend on the test purpose and the nature of the application under test. For
instance, testing of a Web server may require simulating an extensive load, which requires the
recording and playback of HTTP traffic to that server, while testing of an image editor may need
the recording and playback of mouse movements and presses and releases of mouse buttons.
TestComplete lets you simulate these and other actions over the applications under test.
Testing steps may include actions that prepare the application for the test (that is, they put the
application to some initial state).
Also, testing steps may feed corresponding input to the application.
• Check test results (decide how to determine that the test passed successfully or failed).
After the testing actions are finished, the test should check the results against the expected output
and decide whether the test was successful or not. Typically, after the application performed some
actions, something changed in that application: data in an application window can be rearranged, a
new window may be created, a file can be created on or deleted from your hard disk, and so on.
You should determine what facts will be used as the fail (or success) criteria.
• Logging the result (determine how you will log the test result).
The test results can be logged in different ways, for instance, your test scripts can save the full test
results to a file or show an on screen image notifying you that the test run is over.
TestComplete tracks all simulated actions during the test run and saves the information on these
actions to the test log. Of course, you can post custom messages, image, files or file links to the
log. The messages can be organized into folders and each message may use specific font and
background settings to display. The results can be exported to a file, compressed and sent via
e-mail to your co-workers. You can even create a bug report in an issue-tracking system directly
from test results shown in the log. See Test Log for more information.

After you have planned your test, you can create it. The basic test sequence includes the following steps:
1. Define expected output.
2. Feed corresponding input.
3. Gather output.
4. Compare to expected output.
5. Call for attention if the comparison fails.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Creating Tests 37

These items can be divided into a sequence of smaller substeps, each of which will perform a smaller task. We
call these substeps test items.
A TestComplete project holds one or more project items. Some project items (for instance, Script) or their
child elements (script routines) may be used as a source of tests. That is, a project item or its child element may
be used as a test item - it can be “executed” as a test or a subtest. Projects themselves can also be used as test
items: this happens when you create tests for project suites.
What actually happens when you execute a test item is determined by the properties of that test item. For
instance, if a test item executes a script routine, TestComplete will run this routine; if a test item executes the
Script project item, TestComplete will execute the script routine that is specified by the Main Routine property
of that project item. If you command TestComplete to execute a project, TestComplete will perform the test
item defined by the project’s properties.
To create a test in TestComplete:
• Define the test purpose.
• Create source elements for test items (for instance, write or record a script, create a manual or unit
test, record a low-level procedure, etc.). The test items created depend on your application and the
test purpose.
• Specify the execution order of test items.
• Write a script that will check and log the test result (if necessary). This item is optional, because
some test items (for example, low-level procedures) automatically post messages about their
execution to the log. TestComplete provides various ways that let you decide whether the test
passed successfully. These include special functions for comparing images, files and collections of
object properties, script methods and properties that let you check whether a window is visible or
hidden, capture the window image, and so on.

Creating a Test for the Orders Application


The sample Orders application maintains a list of orders. Suppose we need to test whether the application
generates the customer list correctly. In this case --
• Test purpose: The test should check whether the Orders application generates the customer list
properly.
• Testing steps: To generate the customer list, the user should select the Report | Generate customer
list item from the main menu of the Orders application. One way to create a test that checks the
customer list is to write or record a script or record a low-level procedure that will simulate the
desired user actions. You may even create several scripts (or low-level procedures): one of them
may call a form with a button on it, another - simulates user actions over the form, and so forth.
When the user presses the button to generate the customer list, the application calls the routine that
generates the list. A possible alternative to simulating user actions is to call the application’s
routine that generates the list. This requires TestComplete to have access to the internal
application’s objects, methods and properties, so that you can call this routine directly from your
scripts. In order for TestComplete to have access to application internals, the application under test
must be compiled as an Open Application.
Though our sample application is compiled as an Open Application, we will follow the first
approach: we will create a script that will simulate user actions.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


38 Getting Started

• Checking and logging the test result: If the customer list has been generated successfully, the
Orders application creates a file that holds the customer names. To check whether the list was
generated successfully, our test can check whether the file exists and then compare the generated
file with the base-line copy stored earlier. We will write script instructions that will perform the
described checking and post an error message (if necessary) to the test log.
Currently, our sample project does not include script routines, low-level procedures or other project items that
can be used as test items. Also, the test item sequence is not specified. In the next steps we will record a script
routine and then use it as a test item.

Recording a Test Script


This topic provides general information about the recording capabilities offered by TestComplete and
describes how to record a test script for the Orders application.

Requirement: if you use a computer that has several processors or a multiple-core processor
(for example, dual-core CPU) and has Windows XP Service Pack 2, then you must install
the Windows update #896256 in order for TestComplete to be able to record user actions
correctly. The update is available on Microsoft’s web site:
http://support.microsoft.com/kb/896256
Without this update, TestComplete will record user actions incorrectly. For instance, it may
have an invalid order of keypresses or record double-clicks instead of the drag or click
events.

Recording in TestComplete – General Information


With TestComplete you can record scripts, low-level procedures and HTTP traffic. To start the recording,
select Script | Record from TestComplete’s main menu or press Record on the Test Engine toolbar. This
will switch TestComplete to the recording mode and display the Recording toolbar on the screen:

The toolbar contains items that let you pause and stop recording, specify the recorded item (script code,
low-level procedure or HTTP traffic) and perform additional actions during the recording. For instance, using
the Run Tested Application item you can launch a tested application and by using the Add Checkpoint
From List button you can create checkpoints during the recording. You can also insert comments or
additional code when recording scripts. To do this, press Add Text To Script. We recommend that you
comment your script as you record it, since this is when your ideas are the clearest to you.
By default, once you initiate recording, TestComplete automatically starts recording a script. To record a
low-level procedure, use the Record Low-Level Procedure (screen coordinates) or Record
Low-Level Procedure (window coordinates) button. To record HTTP traffic, use the Record an HTTP
Task button. (See Creating and Recording Low-Level Procedures and Traffic Recording in TestComplete
help).

www.automatedqa.com TestComplete by AutomatedQA Corporation


Recording a Test Script 39

TestComplete records scripts as a series of instructions in one of the supported scripting languages: VBScript,
JScript, DelphiScript, C++Script or C#Script. You can use the Code Editor at any time to modify recorded
scripts and to add specific non-recordable commands.
By default, TestComplete always creates a new script routine before recording. You can also record script code
into the current position of the Code Editor. To do this, disable the Always start a new script option. To change
the option, choose Tools | Options from TestComplete’s main menu and then select Engines | Recording in
the ensuing Options dialog. This will display the Recording options on the right of the Options dialog. When
the Always start a new script option is disabled, the way the script is recorded depends on the insertion point
position within the Code Editor window.If the insertion point is somewhere inside a script routine (procedure
or function), the script recorder will insert the recorder code into this position. If the insertion point is outside
an existing routine, the script recorder will create a new routine before recording.
TestComplete automatically creates a name for the new script routine. The name looks like TestN, where N is
a number (1, 2, 3, 4 and so on). If the script unit does not contain any routines, TestComplete uses the name
Test1. If the Test1 routine exists, it uses the name Test2 and so on. That is, TestComplete automatically
chooses the routine name that does not coincide with the names of other routines in the unit. However, this is
possible only if the routines in the unit do not have syntax errors. Else, TestComplete will always name the new
script routine Test1.
To avoid making the script too dependent on the precise screen layout, and to keep it readable and reasonably
short, TestComplete, by default, only records keyboard and mouse events that affect Windows controls.
TestComplete does not, for instance, record the precise path of the mouse between clicks in different places, or
the time elapsed between each keystroke. However, full-detail recording can be activated by simply using the
low-level procedures.
Also by default, TestComplete does not record the delay between user actions. This makes the script faster and
decreases its overall size. If time periods are critical, enable the Real-Time Mode option before recording (you
can change this option in the same Recording Options dialog, in which you modify the Always start a new
script setting described above).When the Real-Time Mode option is enabled, TestComplete records the delay
between user actions. As a result, you will get a larger script, but it will be executed at the same speed as it was
recorded. You can of course remove the needless delay commands, and modify others to make the script run
faster. For further information on options that affect recording, see Recording Options Dialog in TestComplete
help.
When you start script recording, TestComplete automatically turns off the state of the CAPS LOCK key. The
same operation is performed when starting the test run. These actions ensure that TestComplete will correctly
simulate keystrokes.
To record object names, TestComplete uses the process, window and control names that are displayed in the
Object Browser panel. These names can sometimes be too long and hard to understand. However, you can
assign a custom name to an object. If you assign a custom name, the recorded script will use the mapped name
to address the object, so, you will have clearer and more readable code. For more information, see Name
Mapping, Adding Name Mapping Items and Name Mapping and Script Recording in TestComplete help.
You can use keyboard shortcuts to start or finish recording, and to control the recording process and playback.
Shortcuts free you from having to switch to the TestComplete window every time you want to start or stop
recording. To customize the shortcuts, use the Shortcut Options dialog.

For more information on script recording and on recording peculiarities, see the Recording in TestComplete
section in TestComplete help.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


40 Getting Started

Recording a Script for the Orders Application


We are now ready to record a script for the Orders application. Let’s record this script using a usual (non-open)
application:
• Double-click the Orders | TestedApps project item in the Project Explorer panel. TestComplete
will show the list of tested applications in the Workspace. Press the ellipsis button in the
Parameters cell and specify -NotOpenApp or /NotOpenApp in the Command line parameters
field of the resulting dialog. Close the dialog and return to the TestedApps editor.
Select File | Save All from TestComplete’s main menu to save the changes.
• Select Script | Record from the main menu to start recording. Wait until the Recording toolbar
appears.

• Press the down arrow of the Run Tested Applications button and select Orders from the
drop-down list:

When you launch tested applications this way, TestComplete automatically inserts a method call,
which is used to launch a tested application, into the recorded script (you will see the call in the
next step, when we explore the recorded code).
• Wait until the application starts and the application’s main window is shown:

• Switch to the Orders application and select File | Open from its main menu. This will bring
up the standard Open File dialog.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Recording a Test Script 41

• In the dialog, open the MyTable.tbl file that resides in the <TestComplete>\Samples\Open
Apps\OrdersDemo folder.
It is recommended to type the fully-qualified file name into the File name box of the Open File
dialog. Typing instead of using the mouse will help you avoid problems if the Open File dialog
displays a different initial folder when the script is played back later.
After you specified the file, the Orders application will load data from it and display this data in the
main window.

• Select Samuel Clemens in the list of orders.


• Now we will create an image checkpoint --

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


42 Getting Started

ƒ Select Create Region Checkpoint from the Recording toolbar.

This will invoke the Create Region Checkpoint dialog:

ƒ Move the Create Region Checkpoint dialog so that it does not overlap the main window of the
Orders application.

ƒ Click the icon in the dialog, keep the mouse button pressed and move the cursor to the
Orders toolbar. As you move the mouse, TestComplete highlights the window’s control under
the cursor using a red frame.
ƒ When the Orders toolbar is highlighted, release the mouse button. TestComplete will display
the scripting name of the toolbar in the Object box of the Create Region Checkpoint dialog.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Recording a Test Script 43

ƒ Store the toolbar’s image in the Regions collection of the Stores project item:
o Select Create new item in stores. This will specify that TestComplete should add the
toolbar’s image to the Regions collection as a new element.
o Type Toolbar into the Stores picture name box. This box specifies the name of the
Stores element to be created.
o Leave other parameters (Tolerance, Transparent, Include mouse point and Report
difference) unchanged. For more information on them, see Create Region Checkpoint
Dialog in TestComplete help.

o Press OK. TestComplete will display the dialog asking you to add the Stores item to
your project.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


44 Getting Started

ƒ After you add the image, TestComplete will generate script code for the image comparison
and display this code in the Add Text To Script dialog:
Note: The following image displays the comparison instructions in VBScript. The
syntax of the instructions you see in the Add Text To Script dialog on your
computer may differ from what is shown on the image. The actual code you
see depends on the scripting language you have selected for your
TestComplete project on the Creating a Project step.

ƒ Press Add to close this dialog. TestComplete will insert the comparison instructions into the
script code.
• After closing the Add Text to Script dialog, we are back to the Orders application. Click the title of
the application’s main window, to activate the window.
• Move the mouse cursor to the Orders toolbar and press Edit order. This will call the Edit
Order dialog.
• In the dialog, select FamilyAlbum from the Product dropdown list.
• Select the value in the Card Nr edit field by dragging the mouse and then enter 123123123123
as a card number.
• Click OK to close the dialog.
• Now you can export the customer list to a file. To do this:
ƒ Select Report | Generate customer list from the main menu of the Orders application. Orders
will display the Save File dialog.
ƒ Enter C:\CustomerList.txt into the File name edit box of the Save File dialog.
ƒ Click OK to close the dialog.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Analyzing the Recorded Script 45

The application will save the customer list into the specified file.
• Close the Orders window by clicking the X button on the window's caption bar. This will display
the dialog asking if you want to save changes. Press No. Orders will close.
• Press Stop on the Recording toolbar to halt the recording.
In the next step we will analyze the recorded instructions.

Analyzing the Recorded Script


The recorded script is added to and displayed in the Code Editor. Each script appears as a procedure coded in
VBScript, JScript, DelphiScript, C++Script or C#Script. More information about writing scripts is available in
the next topic. This topic only explains the recorded instructions.
To open the Code Editor panel, right-click the Script | Unit1 node in the Project Explorer panel and then
choose Edit from the context menu, or simply double-click the Script | Unit1 node. TestComplete will display
the code of Unit1 in the Workspace panel.
The recorded script code is similar to the code below. Your actual script may differ from this one. For example,
it may have other class names or window indexes if you have recorded the script on a Visual C++ or Delphi
application.

[VBScript]
Sub Test1
Dim p1
Dim w1
Dim w2
Dim w3
Dim w4
TestedApps.Orders.Run
Set p1 = Sys.Process("Orders")
Set w1 = p1.Window("WindowsForms10.Window.8.app3", "*")
Call w1.MainMenu.Click("File|Open...")
Set w2 = p1.Window("#32770", "Open")
Call
w2.Window("ComboBoxEx32").Window("ComboBox").Window("Edit").Keys("C:\Program
Files\Automated QA\TestComplete 6\Samples\Open Apps\OrdersDemo\MyTable.tbl")
w2.Window("Button", "&Open").ClickButton
Call w1.Window("WindowsForms10.SysListView32.app3").ClickItem("Samuel Clemens",
0)
If (Not
Regions.Compare(Sys.Process("Orders").Window("WindowsForms10.Window.8.app3",
"*").Window("WindowsForms10.ToolbarWindow32.app3"), "Toolbar", False, False, True,
0)) Then
Call Log.Error("The regions are not identical.")
End If
Call w1.Click(195, 10)
Call w1.Window("WindowsForms10.ToolbarWindow32.app3").ClickItem(5, False)
Set w2 = p1.Window("WindowsForms10.Window.8.app3", "Order")
Set w3 = w2.Window("WindowsForms10.Window.8.app3")
Call w3.Window("WindowsForms10.COMBOBOX.app3").ClickItem("FamilyAlbum")
Set w4 = w3.Window("WindowsForms10.EDIT.app3", "123456789012")

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


46 Getting Started

Call w4.Drag(82, 7, -97, 2)


Call w4.Keys("123123123123")
w2.Window("WindowsForms10.BUTTON.app3", "OK").ClickButton
Call w1.MainMenu.Click("Report|Generate customer list...")
Set w2 = p1.Window("#32770", "Save As")
Call
w2.Window("ComboBoxEx32").Window("ComboBox").Window("Edit").Keys("c:\CustomerLis
t.txt")
w2.Window("Button", "&Save").ClickButton
w1.Close
p1.Window("#32770", "Confirmation").Window("Button", "&No").ClickButton
End Sub
[JScript]
function Test1()
{
var p1;
var w1;
var w2;
var w3;
var w4;
TestedApps.Orders.Run();
p1 = Sys.Process("Orders");
w1 = p1.Window("WindowsForms10.Window.8.app3", "*");
w1.MainMenu.Click("File|Open...");
w2 = p1.Window("#32770", "Open");
w2.Window("ComboBoxEx32").Window("ComboBox").Window("Edit").Keys("C:\\Program
Files\\Automated QA\\TestComplete 6\\Samples\\Open
Apps\\OrdersDemo\\MyTable.tbl");
w2.Window("Button", "&Open").ClickButton();
w1.Window("WindowsForms10.SysListView32.app3").ClickItem("Samuel Clemens", 0);

if(!Regions.Compare(Sys.Process("Orders").Window("WindowsForms10.Window.8.app3",
"*").Window("WindowsForms10.ToolbarWindow32.app3"), "Toolbar", false, false, true,
0))
Log.Error("The regions are not identical.");
w1.Click(195, 10);
w1.Window("WindowsForms10.ToolbarWindow32.app3").ClickItem(5, false);
w2 = p1.Window("WindowsForms10.Window.8.app3", "Order");
w3 = w2.Window("WindowsForms10.Window.8.app3");
w3.Window("WindowsForms10.COMBOBOX.app3").ClickItem("FamilyAlbum");
w4 = w3.Window("WindowsForms10.EDIT.app3", "123456789012");
w4.Drag(92, 12, -112, 0);
w4.Keys("123123123123");
w2.Window("WindowsForms10.BUTTON.app3", "OK").ClickButton();
w1.MainMenu.Click("Report|Generate customer list...");
w2 = p1.Window("#32770", "Save As");

w2.Window("ComboBoxEx32").Window("ComboBox").Window("Edit").Keys("c:\\CustomerLi
st.txt");
w2.Window("Button", "&Save").ClickButton();
w1.Close();
p1.Window("#32770", "Confirmation").Window("Button", "&No").ClickButton();
}
[DelphiScript]

www.automatedqa.com TestComplete by AutomatedQA Corporation


Analyzing the Recorded Script 47

procedure Test1;
var p1 : OleVariant;
var w1 : OleVariant;
var w2 : OleVariant;
var w3 : OleVariant;
var w4 : OleVariant;
begin
TestedApps.Orders.Run;
p1 := Sys.Process('Orders');
w1 := p1.Window('WindowsForms10.Window.8.app3', '*');
w1.MainMenu.Click('File|Open...');
w2 := p1.Window('#32770', 'Open');
w2.Window('ComboBoxEx32').Window('ComboBox').Window('Edit').Keys('C:\Program
Files\Automated QA\TestComplete 6\Samples\Open Apps\OrdersDemo\MyTable.tbl');
w2.Window('Button', '&Open').ClickButton;
w1.Window('WindowsForms10.SysListView32.app3').ClickItem('Samuel Clemens', 0);
if not
Regions.Compare(Sys.Process('Orders').Window('WindowsForms10.Window.8.app3',
'*').Window('WindowsForms10.ToolbarWindow32.app3'), 'Toolbar', false, false, true,
0) then
Log.Error('The regions are not identical.');
w1.Click(195, 10);
w1.Window('WindowsForms10.ToolbarWindow32.app3').ClickItem(5, false);
w2 := p1.Window('WindowsForms10.Window.8.app3', 'Order');
w3 := w2.Window('WindowsForms10.Window.8.app3');
w3.Window('WindowsForms10.COMBOBOX.app3').ClickItem('FamilyAlbum');
w4 := w3.Window('WindowsForms10.EDIT.app3', '123456789012');
w4.Drag(81, 10, -133, -2);
w4.Keys('123123123123');
w2.Window('WindowsForms10.BUTTON.app3', 'OK').ClickButton;
w1.MainMenu.Click('Report|Generate customer list...');
w2 := p1.Window('#32770', 'Save As');

w2.Window('ComboBoxEx32').Window('ComboBox').Window('Edit').Keys('C:\CustomerLis
t.txt');
w2.Window('Button', '&Save').ClickButton;
w1.Close;
p1.Window('#32770', 'Confirmation').Window('Button', '&No').ClickButton;
end;
[C++Script, C#Script]
function Test1()
{
var p1;
var w1;
var w2;
var w3;
var w4;
TestedApps["Orders"]["Run"]();
p1 = Sys["Process"]("Orders");
w1 = p1["Window"]("WindowsForms10.Window.8.app3", "*");
w1["MainMenu"]["Click"]("File|Open...");
w2 = p1["Window"]("#32770", "Open");

w2["Window"]("ComboBoxEx32")["Window"]("ComboBox")["Window"]("Edit")["Keys"]("C:
\\Program Files\\Automated QA\\TestComplete 6\\Samples\\Open

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


48 Getting Started

Apps\\OrdersDemo\\MyTable.tbl");
w2["Window"]("Button", "&Open")["ClickButton"]();
w1["Window"]("WindowsForms10.SysListView32.app3")["ClickItem"]("Samuel
Clemens", 0);

if(!Regions["Compare"](Sys["Process"]("Orders")["Window"]("WindowsForms10.Window
.8.app3", "*")["Window"]("WindowsForms10.ToolbarWindow32.app3"), "Toolbar",
false, false, true, 0))
Log["Error"]("The regions are not identical.");
w1["Click"](195, 10);
w1["Window"]("WindowsForms10.ToolbarWindow32.app3")["ClickItem"](5, false);
w2 = p1["Window"]("WindowsForms10.Window.8.app3", "Order");
w3 = w2["Window"]("WindowsForms10.Window.8.app3");
w3["Window"]("WindowsForms10.COMBOBOX.app3")["ClickItem"]("FamilyAlbum");
w4 = w3["Window"]("WindowsForms10.EDIT.app3", "123456789012");
w4["Drag"](83, 8, -167, -6);
w4["Keys"]("123123123123");
w2["Window"]("WindowsForms10.BUTTON.app3", "OK")["ClickButton"]();
w1["MainMenu"]["Click"]("Report|Generate customer list...");
w2 = p1["Window"]("#32770", "Save As");

w2["Window"]("ComboBoxEx32")["Window"]("ComboBox")["Window"]("Edit")["Keys"]("C:
\\CustomerList.txt");
w2["Window"]("Button", "&Save")["ClickButton"]();
w1["Close"]();
p1["Window"]("#32770", "Confirmation")["Window"]("Button",
"&No")["ClickButton"]();
}

The script starts with variable declarations. TestComplete automatically detects what objects (process,
windows, controls, etc.) you recorded with user actions and defines the appropriate number of variables.
[VBScript]
Dim p1
Dim w1
Dim w2
Dim w3
Dim w4
[JScript]
var p1;
var w1;
var w2;
var w3;
var w4;
[DelphiScript]
var p1 : OleVariant;
var w1 : OleVariant;
var w2 : OleVariant;
var w3 : OleVariant;
var w4 : OleVariant;
[C++Script, C#Script]

www.automatedqa.com TestComplete by AutomatedQA Corporation


Analyzing the Recorded Script 49

var p1;
var w1;
var w2;
var w3;
var w4;

The variable declarations are followed by this line –


[VBScript]
TestedApps.Orders.Run
[JScript]
TestedApps.Orders.Run();
[DelphiScript]
TestedApps.Orders.Run;
[C++Script, C#Script]
TestedApps["Orders"]["Run"]();
This line launches the Orders application. TestComplete records the line since we launched the application
from the Recording toolbar during the script recording. The TestedApps object provides a scripting interface
to the applications added to the tested applications list. The applications are identified by their name in the list
(in our case, the name is Orders). The Run method launches the application. For more information on
launching tested applications, see Working With Tested Applications in Scripts.

A call to the Run method is followed by this line --


[VBScript]
Set p1 = Sys.Process("Orders.exe")
[JScript]
p1 = Sys.Process("Orders");
[DelphiScript]
p1 := Sys.Process('Orders');
[C++Script, C#Script]
p1 = Sys["Process"]("Orders");

This line calls the Process method of the Sys object. TestComplete provides special program objects to work
with processes and windows from scripts. The Sys.Process(...) method returns the process object that
represents the application (process) in scripts. This returned object is stored to the p1 variable that was defined
at the beginning of our script routine.
The Process method is executed successfully only if the process (that is, the application) exists in the system.
Otherwise, TestComplete will generate an error and post it to the test log.
If you want to check the existence of the process without posting an error message to the log, you can use the
WaitProcess method of the Sys object. This method pauses the script execution until the specified process is

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


50 Getting Started

created or until the specified timeout is reached. If the process does not exist, the method returns an empty stub
object; it does not post an error message to the test log:
[VBScript]
...
' Wait for the process called MyApp for 3000 milliseconds
Set p = Sys.WaitProcess("MyApp", 3000)

' Check whether the process exists


If Not p.Exists Then
' The process does not exist
Else
' The process exists
End If
...
[JScript]
var p;
...
// Wait for the process called MyApp for 3000 milliseconds
p = Sys.WaitProcess("MyApp", 3000);

// Check whether the process exists


if (! p.Exists)
// The process does not exist
else
// The process exists
...
[DelphiScript]
var
p : OleVariant;
begin
...
// Wait for the process called MyApp for 3000 milliseconds
p := Sys.WaitProcess('MyApp', 3000);

// Check whether the process exists


if not p.Exists then
// The process does not exist
else
// The process exists
...
end;
[C++Script, C#Script]
var p;
...
// Wait for the process called MyApp for 3000 milliseconds
p = Sys["WaitProcess"]("MyApp", 3000);

// Check whether the process exists


if (! p["Exists"])
// The process does not exist
else

www.automatedqa.com TestComplete by AutomatedQA Corporation


Analyzing the Recorded Script 51

// The process exists


...

Objects that do not exist are always something to worry about with external scripts dealing with processes or
windows. For instance, you may need to check whether a process exists to detemine whether you can continue
testing or not. To perform this check, use the Exists property (this property belong to all scripting objects that
correspond to processes, windows and controls):
[VBScript]
' Obtain the process
Set p2 = Sys.Process("MyProcess")

' Do something here

' Check whether the process exists


If p2.Exists Then
' Process exists
Else
' Process was closed
End If
[JScript]
// Obtain the process
p2 = Sys.Process("MyProcess");

// Do something here

// Check whether the process exists


if (p2.Exists)
// Process exists
else
// Process was closed
[DelphiScript]
// Obtain the process
p2 := Sys.Process('MyProcess');

// Do something here

// Check whether the process exists


if p2.Exists then
// Process exists
else
// Process was closed
[C++Script, C#Script]
// Obtain the process
p2 = Sys["Process"]("MyProcess");

// Do something here

// Check whether the process exists


if (p2["Exists"])
// Process exists

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


52 Getting Started

else
// Process was closed

Let’s return to the recorded code. The next method after Sys.Process is p1.Window(...) --
[VBScript]
Set w1 = p1.Window("WindowsForms10.Window.8.app3", "*")
[JScript]
w1 = p1.Window("WindowsForms10.Window.8.app3", "*");
[DelphiScript]
w1 := p1.Window('WindowsForms10.Window.8.app3', '*');
[C++Script, C#Script]
w1 = p1["Window"]("WindowsForms10.Window.8.app3", "*");

This is a method of the process object (p1). It returns the window object for a window created by the process.
It uses the window class name, caption and window index (similar to z-order) as parameters. In our case, only
the first two parameters are used; the third one is omitted: TestComplete may not record the index if the class
name and caption are enough for window recognition.
If needed, you may map the “long” process and window names to a shorter and more readable string. See Name
Mapping in TestComplete help.
As you can see, TestComplete recorded the * wildcard instead of the window caption. This was done to make
the script more universal. The window caption is an unstable window attribute. It can be modified several
times during the application run. Replacing the variable part of the window caption with wildcard characters (*
and ?) guarantees that the script will work when the caption is changed.
You can use wildcards in the window class name as well. This is necessary for some MFC windows whose
class name (like Afx:400000:823:10011:0:0) changes from one application run to another. TestComplete
includes a special option that controls how the class names of MFC windows are recorded. This option is called
Auto-correct Afx window classes. If this option is enabled, TestComplete automatically inserts wildcards in the
class name during recording. If the option is disabled, the wildcards are not used. To view or change the option,
choose Tools | Options from TestComplete’s main menu and the select the Engines | Recording category in
the ensuing Options dialog. This will display the Recording settings on the right of the Options dialog.
To specify an asterisk as part of the window caption or class name, use double asterisks (for example,
“MyWndCaption**”).
If the specified window does not exist, the Window() method posts an error message to the test log. Quite
often, you need to check the window existance and do not post any error messages to the log. For instance, the
creation of a window may take some time and you may need to pause the script until the desired window
appears on screen. For this purpose, use the WaitWindow function. This function is similar to the
WaitProcess function that we described above. It delays the execution until the specified window is created
or the specified time period elapses:
[VBScript]
...
' Obtain the process called MyApp
Set p = Sys.Process("MyApp")

www.automatedqa.com TestComplete by AutomatedQA Corporation


Analyzing the Recorded Script 53

' Wait for a window for 3000 milliseconds


Set w = p.WaitWindow("MyWndClass", "MyWndCaption", -1, 3000)
' Check whether the window exists
If w.Exists Then
' The window exists
Else
' The window does not exist
End If
...
[JScript]
var p, w;

...
// Obtain the process called MyApp
p = Sys.Process("MyApp");
// Wait for a window for 3000 milliseconds
w = p.WaitWindow("MyWndClass", "MyWndCaption", -1, 3000);
// Check whether the window exists
if(w.Exists)
// The window exists
else
// The window does not exist
...
[DelphiScript]
var
p, w : OleVariant;
begin
...
// Obtain the process called MyApp
p := Sys.Process('MyApp');
// Wait for a window for 3000 milliseconds
w := p.WaitWindow('MyWndClass', 'MyWndCaption', -1, 3000);
// Check whether the window exists
if w.Exists then
// The window exists
else
// The window does not exist
...
end;
[c++Script, C#Script]
var p, w;
...
// Obtain the process called MyApp
p = Sys["Process"]("MyApp");
// Wait for a window for 3000 milliseconds
w = p["WaitWindow"]("MyWndClass", "MyWndCaption", -1, 3000);
// Check whether the window exists
if(w["Exists"])
// The window exists
else
// The window does not exist
...

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


54 Getting Started

Another way to pause the script until the desired window appears on screen is to use the process.Window()
method and increase the value of the Auto-wait timeout project property. This property specifies the number of
milliseconds TestComplete will wait when you address a process, window or control in scripts and this
process, window or control is not available for some reaons. To change the property, right-click the project in
the Project Explorer panel and select Edit | Properties from the context menu. TestComplete will open the
project editor in the Workspace panel activate the editor’s Properties page. Choose the Playback category
from the list that resides on the left of the page. The settings will be displayed to the right of the categories list.
For more information on pausing the script and waiting for windows and processes, see Waiting for a Process
or Window Activation, Waiting for Object State Changes, Delaying the Script Execution and WaitChild in
TestComplete help.
Note that we launched the Orders application as a non-Open application. We do this intentionally to
demonstrate how TestComplete addresses windows of ordinary (non-Open) applications. However, if you
launch the C# version of the Orders application without the NotOpenApp command-line argument, the
application will become Open to TestComplete and to address forms, controls and objects, TestComplete will
use names defined in the applications source code. For more information, see How TestComplete Recognizes
Processes, Windows and Controls.

The next line in the script is --


[VBScript]
Call w1.MainMenu.Click("File|Open...")
[JScript]
w1.MainMenu.Click("File|Open...");
[DelphiScript]
w1.MainMenu.Click('File|Open...');
[C++Script, C#Script]
w1["MainMenu"]["Click"]("File|Open...");

It selects File | Open from Orders’ main menu. The name of the desired menu item is passed to the Click
method of the MainMenu object. Item names in the item “path” are separated by vertical lines.
Note that you can address menu items by either their names, or by indexes. The menu item names can be used
if the menu item has no picture and the application displays the item in the standard way (that is, if the style of
menu items is not MFT_BITMAP or MFT_OWNERDRAW). Indexes let you work with menu items that cannot be
addressed by their captions. Of course, item names make the script more readable, but indexes are more
universal and work for almost all item types. If you are not sure how to address menu items, we recommend
that you use indexes. See also Simulating User Actions in TestComplete help.

These lines come after a menu item is selected:


[VBScript]
Set w2 = p1.Window("#32770", "Open")
Call
w2.Window("ComboBoxEx32").Window("ComboBox").Window("Edit").Keys("C:\Program
Files\Automated QA\TestComplete 6\Samples\Open Apps\OrdersDemo\MyTable.tbl")
w2.Window("Button", "&Open").ClickButton

www.automatedqa.com TestComplete by AutomatedQA Corporation


Analyzing the Recorded Script 55

[JScript]
w2 = p1.Window("#32770", "Open");
w2.Window("ComboBoxEx32").Window("ComboBox").Window("Edit").Keys("C:\\Program
Files\\Automated QA\\TestComplete 6\\Samples\\Open
Apps\\OrdersDemo\\MyTable.tbl");
w2.Window("Button", "&Open").ClickButton();
[DelphiScript]
w2 := p1.Window('#32770', 'Open');
w2.Window('ComboBoxEx32').Window('ComboBox').Window('Edit').Keys('C:\Program
Files\Automated QA\TestComplete 6\Samples\Open Apps\OrdersDemo\MyTable.tbl');
w2.Window('Button', '&Open').ClickButton;
[C++Script, C#Script]
w2 = p1["Window"]("#32770", "Open");
w2["Window"]("ComboBoxEx32")["Window"]("ComboBox")["Window"]("Edit")["Keys"]("C:
\\Program Files\\Automated QA\\TestComplete 6\\Samples\\Open
Apps\\OrdersDemo\\MyTable.tbl");
w2["Window"]("Button", "&Open")["ClickButton"]();

The first line returns the window object that corresponds to the standard Open File dialog. The second line
simulates typing of the file name in the File Name field of the dialog. The simulation is performed by the Keys
method. TestComplete automatically adds it to windows, which can accept keyboard input.
The next line in the script –
[VBScript]
w2.Window("Button", "&Open").ClickButton
[JScript]
w2.Window("Button", "&Open").ClickButton();
[DelphiScript]
w2.Window('Button', '&Open').ClickButton;
[C++Script, C#Script]
w2["Window"]("Button", "&Open")["ClickButton"]();

-- simulates pressing the Open button in the dialog. Pressing this button closes the Open File dialog.
Note: When recording a script, TestComplete uses the same process, window and control
names that are displayed in the Object Browser panel. These names uniquely identify the
object of the application under test, but can sometimes be too long and hard to
understand. You can create a custom name for an object by using Name Mapping
functionality and TestComplete will use this name during recording. By using the Name
Mapping feature you will have clearer and more readable code. For more information on
name mapping, creating custom names and using them when recording scripts, see Name
Mapping, Adding Name Mapping Items and Name Mapping and Script Recording in
TestComplete help.

The next instruction in the script returns us to Orders’ main window and simulates a mouse click on the Samuel
Clemens node in the list:

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


56 Getting Started

[VBScript]
Call w1.Window("WindowsForms10.SysListView32.app3").ClickItem("Samuel Clemens",
0)
[JScript]
w1.Window("WindowsForms10.SysListView32.app3").ClickItem("Samuel Clemens", 0);
[DelphiScript]
w1.Window('WindowsForms10.SysListView32.app3').ClickItem('Samuel Clemens', 0);
[C++Script, C#Script]
w1["Window"]("WindowsForms10.SysListView32.app3")["ClickItem"]("Samuel Clemens",
0);

Note that we do not use any special command to activate the window where the script will “send” the click.
TestComplete automatically activates the appropriate window.
Also note, that the window caption is not used to address the list view control on the main form of the Orders
application (Window("WindowsForms10.SysListView32.app3")). The name is omitted because the
form only contains one control with the class name WindowsForms10.SysListView32.app3.
The ClickItem method simulates a mouse click on the Samuel Clemens item in the list view. TestComplete
automatically adds the ClickItem method to any window object that it recognizes as a list view control. To
determine that a window is a list view window, TestComplete checks the window class name with the name
given by default to windows of this type. If the check is successful, TestComplete treats the window as a list
view control. Similarly, TestComplete determines the type of other windows. If the window class name differs
from the default name, TestComplete uses Object Mapping settings to determine the window type. Once
TestComplete determines the window type it adds methods and properties specific to windows of that type to
the window object. All of TestComplete’s program objects for Windows controls have several methods to
simulate mouse clicks within the controls. These methods let you simulate the click of an item displayed in the
control or simulate mouse clicks using specified coordinates.

Now we have reached the instructions that were inserted into the script when we saved an image during
recording:
[VBScript]
If (Not
Regions.Compare(Sys.Process("Orders").Window("WindowsForms10.Window.8.app3",
"*").Window("WindowsForms10.ToolbarWindow32.app3"), "Toolbar", False, False, True,
0)) Then
Call Log.Error("The regions are not identical.")
End If
[JScript]
if(!Regions.Compare(Sys.Process("Orders").Window("WindowsForms10.Window.8.app3",
"*").Window("WindowsForms10.ToolbarWindow32.app3"), "Toolbar", false, false, true,
0))
Log.Error("The regions are not identical.");
[DelphiScript]

www.automatedqa.com TestComplete by AutomatedQA Corporation


Analyzing the Recorded Script 57

if not
Regions.Compare(Sys.Process('Orders').Window('WindowsForms10.Window.8.app3',
'*').Window('WindowsForms10.ToolbarWindow32.app3'), 'Toolbar', false, false, true,
0) then
Log.Error('The regions are not identical.');
[C++Script, C#Script]
if(!Regions["Compare"](Sys["Process"]("Orders")["Window"]("WindowsForms10.Window
.8.app3", "*")["Window"]("WindowsForms10.ToolbarWindow32.app3"), "Toolbar",
false, false, true, 0))
Log["Error"]("The regions are not identical.");

The Regions.Compare method is used to compare images. The method’s first parameter is the control on the
screen and the second parameter specifies the picture which was saved to the Regions collection of the
Stores project item as Toolbar. The other parameters allow you to exclude transparent pixels from comparison
and take into account the mouse cursor image. For complete information on them, see method description in
TestComplete help.
TestComplete provides similar comparison methods for files, object properties, databases, XML documents,
web pages and other elements saved to the Stores project item. For more information, see About Checkpoints in
TestComplete help.
You may wonder why you would need a comparison. The developers can change the toolbar and performing a
comparison lets you check for this, before assuming your script is still pressing the right buttons. Due to the
way the inserted code is written, you will get a log message if the comparison fails.
A more advanced solution would be to modify the script so that it is not dependant on button location: you can
find the button image on the toolbar using the Regions.Find method and then simulate a mouse click in the
found area. The only requirement is that you must first save the image of the button you are looking for to a
file. For more information on this, see Comparing and Finding Images and description of the Regions.Find
method in TestComplete help.
Note: It is recommended that you capture and save images using TestComplete, or capture
images using the Windows shortcuts (ALT-PRTSCN or PRTSCN) and save them using
MSPaint. Other screenshot applications may save the images with errors, which may
cause incorrect results of image comparisons and finding operations.

The next script lines are --


[VBScript]
Call w1.Click(195, 10)
Call w1.Window("WindowsForms10.ToolbarWindow32.app3").ClickItem(5, False)
[JScript]
w1.Click(195, 10);
w1.Window("WindowsForms10.ToolbarWindow32.app3").ClickItem(5, false);
[DelphiScript]
w1.Click(195, 10);
w1.Window('WindowsForms10.ToolbarWindow32.app3').ClickItem(5, false);
[C++Script, C#Script]

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


58 Getting Started

w1["Click"](195, 10);
w1["Window"]("WindowsForms10.ToolbarWindow32.app3")["ClickItem"](5, false);

The first line simulates the mouse click over the title of the Orders application’s window. We did this click to
activate the window since it had been inactive after we created the region checkpoint.
The second line simulates the selection of the Edit order button of the application’s toolbar. To perform this
action, we use the ClickItem method. TestComplete automatically adds it to the objects, which it recognizes
as toolbars. 5 is the button’s position on the toolbar (the ClickItem method can address the toolbar items by
their captions, position or id. For more information, see the method description in TestComplete help).

The rest of the script code does not require any further explanation. It contains --
• Instructions that simulate user actions in the Edit order dialog.
• Instructions that simulate user actions when generating the customer list.
• Code used to close the application window and simulate user actions for the Save Changes request.
All methods and properties used here have been explained above.

Editing and Writing Scripts


General Notes
In many cases it is convenient to first record a script and then modify it in the Code Editor. However,
sometimes it may make sense for you to create new scripts manually without recording anything. The Code
Editor works well for this. It offers all modern editing features:
• Syntax highlighting
• Outlining
• Code templates
• Code navigation
• Text search and replace
• Clipboard capacities
• Etc.
The Code Editor has a Code Completion window with a list of objects and global functions which you can use
in your scripts. See the Code Editor description in TestComplete help for a detailed overview of all Editor
features. Of course, script code is text and you can edit it in any text editor.
For more information on writing script code in TestComplete, please see Scripting in TestComplete help.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Editing and Writing Scripts 59

Writing Comparison Code


The goal of our test is to compare whether the Orders application generates the customer list correctly. We
recorded a script simulating user actions that export a list to a file. Now we have to write script code that
compares the baseline copy of this file with the copy that will be generated by the script.
We will use the C:\CustomerList.txt file generated during the script recording as the baseline copy. Now we
should add this file to our TestComplete project:
• Activate TestComplete’s Project Explorer panel.
• Right-click the Stores | Files node in the Project Explorer and select Add | New Item from the
context menu. TestComplete will show the standard Open File dialog, where you can select the
file to be added to the project.
• In the dialog select the file C:\CustomerList.txt and click Open. TestComplete will display the
message box asking you whether it should copy the file to the Stores folder of your project.
Answer Yes. TestComplete will copy the file to the Stores folder and then add the copy to the Files
collection of the Stores project item. The added file will be displayed under the Stores | Files node
in the Project Explorer:

• Open Windows Explorer or any other file manager and delete the C:\CustomerList.txt file. If you
leave the file, then during the script run you will get a message box asking you whether to replace
the existing file or not. This message box is an unexpected window for TestComplete since it did
not exist during the script recording. TestComplete is able to handle unexpected windows
appropriately (see Handling Unexpected Windows in TestComplete help). TestComplete will
handle the message box by clicking its default button. However, it will post an error message about
the window in the test log. So, the log will report that an error occurred during testing (despite the
fact that this error was not significat and TestComplete was able to handle it). Deleting the file
solves the problem with the error message.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


60 Getting Started

Now we can write script code that will compare the files. You can write the comparison code manually, or
generate the code using the Create File Checkpoint dialog. Let’s use the dialog:

• To call the dialog, select Create File Checkpoint from the Tools toolbar (if the toolbar is
hidden, right-click within the toolbar area and choose Tools from the ensuing toolbars list):

TestComplete will display the dialog on screen:

• The files to be compared are specified in the File 1 and File 2 boxes of the dialog. Press the ellipsis
button of the File 1 box and select the C:\CustomerList.txt file in the ensuing Open File dialog.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Editing and Writing Scripts 61

• To specify the other file for comparison, press the down arrow button of the File 2 box and choose
CustomerList.txt from the drop-down list (the drop-down list displays the elements of the Stores
| Files collection).

• Press OK. TestComplete will generate the file comparison code and display it in the Copy Text to
Clipboard dialog. The generated code looks as follows:
[VBScript]
If (Not Files.Compare("C:\CustomerList.txt", "CustomerList.txt", 0,
True)) Then
Call Log.Error("The files are not identical.")
End If
[JScript]
if(!Files.Compare("C:\\CustomerList.txt", "CustomerList.txt", 0, true))
Log.Error("The files are not identical.");
[DelphiScript]
if not Files.Compare('C:\CustomerList.txt', 'CustomerList.txt', 0, true)
then
Log.Error('The files are not identical.');
[C++Script, C#Script]
if(!Files["Compare"]("C:\\CustomerList.txt", "CustomerList.txt", 0,
true))
Log["Error"]("The files are not identical.");

As you can see, to compare the files, TestComplete uses the Files.Compare method with two
parameters. One parameter specifies the file holding the exported data and the other specifies the
file hodling the baseline copy of the data. Both parameters can point to files that reside on the hard
drive, or to elements of the Files collection. For more information on comparing files, see File
Checkpoints in TestComplete help.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


62 Getting Started

• In our example, we will modify the generated code: we will place it within a routine and add the
else statement. You can edit the code directly in the Copy Text to Clipboard dialog. The resultant
version looks like –
[VBScript]
Sub CompareFiles
If (Not Files.Compare("C:\CustomerList.txt", "CustomerList.txt", 0,
True)) Then
Call Log.Error("The files are not identical.")
Else
Call Log.Message("The files are identical.")
End If
Call Utilities.DeleteFile("C:\CustomerList.txt")
End Sub
[JScript]
function CompareFiles()
{
if(!Files.Compare("C:\\CustomerList.txt", "CustomerList.txt", 0,
true))
Log.Error("The files are not identical.");
else
Log.Message("The files are identical.");
Utilities.DeleteFile("C:\\CustomerList.txt");
}
[DelphiScript]
procedure CompareFiles;
begin
if not Files.Compare('C:\CustomerList.txt', 'CustomerList.txt', 0,
true) then
Log.Error('The files are not identical.')
else
Log.Message('The files are identical.');
Utilities.DeleteFile('C:\CustomerList.txt');
end;
[C++Script, C#Script]
function CompareFiles()
{
if(! Files["Compare"]("C:\\CustomerList.txt", "CustomerList.txt", 0,
true))
Log["Error"]("The files are not identical.");
else
Log["Message"]("The files are identical.");
Utilities["DeleteFile"]("C:\\CustomerList.txt");
}

• Press Copy to copy the code to the clipboard and to close the dialog.
• Switch to the Code Editor and paste the copied code to your script unit.
• Select File | Save All from TestComplete’s main menu to save the changes.
In the next step we will include the CompareFiles routine into testing tasks and execute the test.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Specifying Execution Order for Tests 63

Specifying Execution Order for Tests


A test may include several subtests, each of which performs a smaller testing task. We say that test consists of
test items. Each test item is associated with a script routine, low-level procedure, manual test, unit test or
another project element that can be executed as a test.
You create the desired test items, specify their execution flow and modify properties on the Test Items page of
the project editor. To open this page, right-click the project in the Project Explorer panel and choose Edit | Test
Items from the context menu. TestComplete will open the project editor in the Workspace panel and activate
the editor’s Test Items page. The page shows a tree-like structure of existing test items and lets you modify this
structure as needed. The following image displays a sample Test Items page:

Test Items Page (Project Editor)

Note that the project suite editor also contains the Test Items page. It lets you specify the execution order of
projects, which belong to this suite, by dragging the projects in the page:

Test Items Page (Project Suite Editor)

The difference between these pages is obvious: when you command TestComplete to execute a project,
TestComplete will run tests defined with the Test Items page of the project editor. When you command
TestComplete to execute a project suite, it will execute projects in the order specified on the Test Items page of
the project suite editor.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


64 Getting Started

By default, for each new project, TestComplete creates a new test item that launches the routine specified by
the Main routine property of the Script’s project item. Let’s create new test items for script routines that we
created on previous steps:
• Open the Test Items page by double-clicking the project node in the Project Explorer panel.
TestComplete will show the project editor in the Workspace panel.
• Click Test Items at the bottom of the editor. TestComplete will open the Test Items edit page
containing a tree-like structure of test items. By default, the page has only one test item that is
associated with the main routine of the Script project item.

Let’s modify the properties of the existing test item so that it will be associated with the recorded
script routine (Test1), but not with the main routine.
• To specify the test item’s source, press the ellipsis button of the Element to be run column. This
will call the Select Test Item dialog.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Specifying Execution Order for Tests 65

• In the Select Test Item dialog choose Script | Unit1 | Test1 (the recorded script routine) and then
click OK to save.

TestComplete will display the selected element in the Element to be run column.
Now let’s add a test item for the CompareFiles routine we created in the previous step:
• Right-click somewhere within the Test Item's edit page and choose New Item from the context
menu. TestComplete will create a new empty test item.
• To specify the test item’s source, press the ellipsis button of the Element to be run column. This
will call the Select Test Item dialog.
• In the Select Test Item dialog choose Script | Unit1 | CompareFiles and click OK. TestComplete
will display the selected element in the Element to be run column.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


66 Getting Started

Now the Test Items page contains two test items associated with script routines:

• Once you have created a new test item, you can modify its properties in a column of the
Workspace panel. For instance, you can change the Count property to specify the number of times
the test item will be executed, or modify the Timeout property to set the maximum time period for
an item’s execution. If the test item’s execution time exceeds the specified timeout, TestComplete
terminates the test item run and considers that the item failed to execute successfully. For more
information on the properties that you can edit on the page, see Test Items Edit Page in
TestComplete help.
To modify a property, click it twice (not double-click) on the page or select the property and press
F2.
In our example, we will not modify the item’s properties.
Note: Make sure that the test item is enabled, that is, the checkbox on the left of the test
item’s icon is selected. TestComplete executes a test item only if it is enabled.
We only created two test items. They will perform all of the steps described in the Creating Tests topic: they
will launch the tested application, simulate user actions over it, save the list of customers to the file and
compare it with a baseline copy. This is enough for our sample project. In real-life projects, you will typically
need to create more than two test items. You can create as many test items as needed.
To change the position of a test item, drag it to the desired node in the Test Items page, or right-click the item
and use the Move Up, Move Down, Indent and Outdent items of the context menu.
To remove a test item, select it in the Workspace and then choose Delete from the context menu.
Note: Test execution can be initiated from a script. That is, your project may contain only one
test item that will refer to the Script’s main routine and all other script routines, low-level
procedures, unit tests, manual tests, and so forth, can be called from this main routine. For
information on how to do this, see Calling Project Elements From Scripts in
TestComplete help.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Running the Created Tests 67

Running the Created Tests


Before running tests, you should have completed the following preliminary steps:
• Define the test’s purpose.
• Create test items.
• Specify the test item’s execution order.
TestComplete can use different kinds of tests: scripts, low-level procedures, and so forth. Some of these tests
can be recorded. Therefore, before running tests, make sure they start with the same initial conditions as the
recording did. For instance, the script almost always requires the tested application to be running. So, before
simulating the user actions, you should launch the application. To guarantee that the application is loaded, do
one of the following:
• Right-click the application’s node in the Project Explorer panel and choose Run from the context
menu (the tested applications are displayed as child items of the TestedApps item in the panel).
To launch all tested applications, right-click the TestedApps item and choose Run All from the
context menu.
Similarly, you can launch applications from the Tested Applications editor that is displayed in the
Workspace panel.
-- or --
• Call the TestedApps.AppName.Run method at the beginning of the script. Our recorded script
already contains this method call, since we started the Orders application from the Recording
toolbar (when you do this, TestComplete automatically adds the method call to the recorded
script):
[VBScript]
Sub Test1
Dim p1
Dim w1
Dim w2
Dim w3
Dim w4
TestedApps.Orders.Run
Set p1 = Sys.Process("Orders")
...
[JScript]
function Test1()
{
var p1;
var w1;
var w2;
var w3;
var w4;
TestedApps.Orders.Run();
p1 = Sys.Process("Orders");
...
[DelphiScript]

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


68 Getting Started

procedure Test1;
var p1 : OleVariant;
var w1 : OleVariant;
var w2 : OleVariant;
var w3 : OleVariant;
var w4 : OleVariant;
begin
TestedApps.Orders.Run();
p1 := Sys.Process('Orders');
...
[C++Script, C#Script]
function Test1()
{
var p1;
var w1;
var w2;
var w3;
var w4;
TestedApps["Orders"]["Run"]();
p1 = Sys["Process"]("Orders");
...

To launch all tested applications, you can call the TestedApps.RunAll method at the beginning
of the testing script.
[VBScript]
Sub Test1
Dim p1
Dim w1
Dim w2
Dim w3
Dim w4
TestedApps.RunAll
Set p1 = Sys.Process("Orders")
...
[JScript]
function Test1()
{
var p1;
var w1;
var w2;
var w3;
var w4;
TestedApps.RunAll();
p1 = Sys.Process("Orders");
...
[DelphiScript]
procedure Test1;
var p1 : OleVariant;
var w1 : OleVariant;
var w2 : OleVariant;
var w3 : OleVariant;

www.automatedqa.com TestComplete by AutomatedQA Corporation


Running the Created Tests 69

var w4 : OleVariant;
begin
TestedApps.RunAll();
p1 := Sys.Process('Orders');
...
[C++Script, C#Script]
function Test1()
{
var p1;
var w1;
var w2;
var w3;
var w4;
TestedApps["RunAll"]();
p1 = Sys["Process"]("Orders");
...

Despite of the way you launch a tested application (via the menu item or with a method call), TestComplete
will launch the application according to the run mode specified in the TestedApps editor.
If you launch an application under Windows Vista or Windows Server 2008 with administrator privileges, the
operating system will display a dialog box asking for your permission for the run. Due to certain limitations,
the closing of this dialog box cannot be automated (when this dialog box is visible, the script run is paused).
You should either close the dialog manually, or modify User Account Control setttings so that Windows does
not display the dialog. See Testing Applications With TestComplete Under Windows Vista and Windows
Server 2008 in TestComplete help.
The created tests are not compiled into an executable for test runs. You run the tests directly from
TestComplete. To run tests on computers that do not have TestComplete installed, you can use a
resource-friendly utility called TestExecute. You can also export script code to an external application and run
it there. For more information on this, see Connected and Self-Testing Applications in TestComplete help.
To run your test:
• Go to the Project Explorer panel (if this panel is hidden, select View | Project Explorer from
TestComplete’s main menu).

• Click Run Project on the panel’s toolbar.


You can also start the project execution by pressing SHIFT-F3. This shortcut can be changed in
the Global Shortcut Options dialog. To display this dialog, choose Tools | Options from the main
menu of TestComplete and then select the General | Global Shortcuts in the ensuing Options
dialog.
Not only can you execute projects, but any element that provides one or more tests: for example, a project suite,
the Script project item, a low-level procedure, and so forth. To run the element, right-click it in the Project
Explorer panel and select Run from the context menu. For instance:
• To “execute” the Script project item, right-click this project item and choose Run from the context
menu. TestComplete will run the routine that is specified by the Main Routine property of the
Script project item.
• To run an individual script routine, right-click the unit holding that routine and choose the desired
script routine from the Run submenu of the context menu.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


70 Getting Started

• To “execute” the project suite, right-click the project suite node and choose Run, or select Run
Project Suite from the Project Explorer toolbar.
The test execution will last until the execution of all test items is over. You can stop the execution at any time
by pressing Stop on the Test Engine toolbar or select Script | Stop from TestComplete’s main menu.
You can pause the test execution by clicking Pause on the Debug toolbar (if the toolbar is hidden,
right-click somewhere within the toolbar area and choose Debug from the ensuing context menu). You can
also pause the test execution by pressing the Pause script execution shortcut (you can modify this shortcut in
the Global Shortcuts Dialog).
When paused you can perform any actions needed. For instance, you can close certain applications or explore
the script variables and objects using TestComplete’s Watch List or Locals panel or the Evaluate dialog (see
Debugging Scripts in TestComplete help). Also, if the Show Log on pause option is enabled, TestComplete
displays the Pause Log window when you pause the test run. In this window you can review test results saved
to the log when paused. The window is closed after you resume the test execution. To view or change the Show
Log on pause option, choose Tools | Options from TestComplete’s main menu and choose the Engines | Log
settings group on the left part of the ensuing Options dialog. TestComplete will display the log settings on the
right of the Options dialog.
After the test execution is over, you can view test results using TestComplete’s test log. The next topic
provides a brief overview of the log capabilities.
For complete information on running tests in TestComplete, on project settings that affect the runs and on the
test execution peculiarities, see Running Tests in TestComplete help.

Analyzing Test Results


TestComplete keeps a complete log of all operations performed during testing. You can add your own notes,
references or images to the log as well.
By default, TestComplete stores the results of each test run in subfolders of the <Project>\Log folder (you can
specify another folder for the log files using the Log location project property). Each subfolder name includes
the name of the executed test including the date and time of the run.
The titles of test results are shown in the Project Explorer panel under the Project_Suite_Name Log |
Project_Name Log node, for example, ProjectSuite1 Log | Project1 Log. It is the primary workspace for
looking up the test history of the project and project suite. Each node corresponds to a test run. An image to the
left of the node specifies whether the corresponding test run passed successfully.
By default, projects store references to all log files. That is, the number of references kept by the project equals
to the number of test runs. This number increases as the testing progresses, and, if the number of references is
too large, you can remove the unnecessary logs by right-clicking them in the Project Explorer panel and
selecting Delete from the context menu. To add existing log files to your project, right-click the Project Log
node and selecting Add Log File from the context menu.
You can also limit the number of references kept by using the Number of recent logs to keep option. To view or
change it, select Tools | Options from TestComplete’s main menu and on the left of the ensuing Options
dialog, choose the Engines | Log group. TestComplete displays the log settings on the right of the dialog. The
option specifies the number of log files stored in the project. If the option is enabled, newer log files will push
out older log files from the list of stored results when the number of references exceeds the option value.
TestComplete will delete both references to files and the files themselves, so if you want to store test results

www.automatedqa.com TestComplete by AutomatedQA Corporation


Analyzing Test Results 71

you should copy them. You can add the saved copy of the results to your project any time later as it is described
above.
Note: TestComplete automatically adds nodes for the last results after the test execution is over.
That is, the results are not displayed when the test is running. You have to wait until the
test run is over.
However, you can view intermediate results if you pause the test execution.
TestComplete includes a special Show Log on pause option. You can find it in the same
Log Options dialog, in which the above-mentioned Number of recent logs to keep option
resides. If the Show Log on pause option is enabled, then during the pause, TestComplete
displays the Pause Log window in the Workspace panel. The window is closed once you
resume the test execution. The pause log is not added to the test log tree displayed in the
Project Explorer.
To view the detailed test results, right-click the desired result in the Project Explorer panel and choose Open
from the context menu. TestComplete will display the test results in the Workspace panel. In our example, the
log is as follows --

The test results’ window shows results of one test run. On the left of the window there is a tree-like structure of
the test that was executed during the test run. The tree reflects the hierarchy and flow of the executed tests and
includes results of all executed test items: scripts, low-level procedures, unit tests and others. For instance, if
you initiated load testing from a script, the Script log tree node will have a child node named Load testing log.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


72 Getting Started

If an event handling routine (script) was executed during the load testing run, the Load testing log node will
hold another Script log node as a child.
In our case, we executed the project that has two test items with each one running a script routine. Let’s explore
the test log nodes.
The root node of the tree corresponds to the start item of the test. In our case the root element corresponds to a
project, since we ran the project. But if we ran a project suite, the root element would correspond to the project
suite; if we ran the Script project item, the root element will be the Script log, and so on.
The root node has two child nodes. They correspond to test items that were executed by the project. Each of
these test items executes one element - the script routine that is specified by the Element to be run column of
the project editor’s Test Items page. The script logs are shown as child nodes of the test item nodes.
An image to the left of the node shows whether the test was successful and if errors or warnings occurred
during its execution. TestComplete can generate error or warning messages to pinpoint application errors, as
well as generate notifications for actions such as keypresses. Scripts can post any kind of message (see Posting
Messages to the Log in TestComplete help). By expanding the nodes with error (or warning) icons, you can
easily find which test operation failed to execute successfully.
To view detailed results for a node, simply select it from the log tree. TestComplete will display detailed results
on the right. Note that every project item has its own results presentation, so what the log window displays is
determined by what project item was used as a source of the test. For instance, the Script project item forms a
log of records with informative, error, warning and picture messages (see the image above). The Remarks
pane of the script test log contains additional information about the currently selected message. The Picture
pane shows an image posted to the log. You can rearrange the log panels as it is described in the Arranging
Columns, Lines and Panels topic in TestComplete help. For instance, you can resize the Remarks or Picture
panes, sort the contents on the Time column, filter results by their type, and do a lot more.
To view a script line that post a message to the test log, double-click the desired message in the log.
TestComplete will open the script unit and position the cursor at the appropriate script line.
The next topic of the Getting Started section, Searching for the Reason of an Error, describes how you can
determine why your test failed to run successfully.

Searching for the Reason of an Error


It is possible that the first versions of your test scripts will fail to execute successfully. There can be a lot of
reasons for this. For instance, the script code may contain a mistaken instruction, the application behavior can
differ from what you expected or an unexpected window may appear during the script run. You can search for
the cause of an error in the following way:
• Look at the first error in the test log (to view the script function that posted this error to the log,
double-click the message in the log window).
• Run your script once again to analyze the application state when an error occurs. To perform this analysis
you can --
ƒ Set breakpoints or pause the test execution and use the Watch List or Locals panel and the
Evaluate dialog to explore test objects and variables’ values (see Debugging Scripts in
TestComplete help).
ƒ Add script statements that will post different diagnostic messages to the log, for example:

www.automatedqa.com TestComplete by AutomatedQA Corporation


Searching for the Reason of an Error 73

- The list of child objects (windows).


- Images of one or several application windows.
- The state of objects (windows): existence, visibility, and so on. For instance, to see if an
object or window exists, use the Exists property; to see if a window or an onscreen
object is visible, you can use the Visible and VisibleOnScreen properties; to see if
an object (window) is enabled or focused, use the Enabled and Focused properties.
The goal of the analysis is to answer the following questions:
• What is the difference between the current application state and the state you expect?
• What is the cause of the error: an error or typo in the script, an application bug or something else?
If you cannot determine the cause of an error, send a message to AutomatedQA’s support team (see Technical
Support and Resources). In order for the support team to answer the message in a timely manner, please attach
your script and archived results folder of your TestComplete project to the message (the project results folder is
normally <Your_Project_Folder>\Log directory). Please modify the script so that it gives detailed information
on your application state at the moment of an error: images of application windows, the list of child objects of
the tested process, and so on. A small sample application that illustrates the problem will be greatly
appreciated.
You can also ask about the problem in our newsgroup or search for a solution in the list of frequently asked
questions. For more information on this, see Technical Support and Resources.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


74 Scripting

Scripting

Writing Scripts – Overview


About Scripts
There are two basic ways to create a script:
• Record a script using TestComplete’s script recorder (see Recording a Test Script in
TestComplete help).
-- or --
• Write a script in TestComplete’s Code Editor.
The easiest way to begin scripting is to use the recorder. The script can be edited further through the Code
Editor.
A script is a procedure or function in one of the supported scripting languages (see the Scripting Languages
section below). Scripts are grouped into unit files, and each project may use as many units as needed. In the
hierarchy of project elements, all the units belong to the Script project item. When you create a new project,
TestComplete automatically creates the Script project item with one unit in it.
A typical script that simulates user actions contains the following statements:
• Sys.Process(…) - This method returns an object that provides a scripting interface to the
process of the tested application.
• processObj.Window(…), windowObj.Window(…) - These methods return windows of objects
or child windows of a parent window (controls on an application form).
• windowObj.Click, windowObj.DblClick, etc., - These statements simulate user actions over
a window.
For more information on these instructions, see How TestComplete Recognizes Processes, Windows and
Controls and Simulating User Actions in TestComplete help.
Scripts may be called from other scripts, by name if in the same unit, else using the <unit name>.<script>
format. You can also import units of other projects. See Calling Routines and Variables Declared in Another
Project in TestComplete help.

Note: Since the unit name can be used in script code, the unit name should be a valid script
identifier and it should not coincide with the name of an existing programming object. If
the unit name is invalid, you have to rename the unit. You can do this in the same way you
rename any other project items. See Renaming Projects, Project Suites and Project Items
in TestComplete help.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Writing Scripts – Overview 75

Whenever you run a command execution of any script, TestComplete checks all script units for syntax errors.
The script will not be run if syntax errors are found. You can check syntax by right-clicking the desired unit in
the Project Explorer and selecting Check Syntax from the context menu.

Scripting Languages
The scripting language for the project is specified during the project’s creation. You can choose from one of
the five scripting languages: VBScript, JScript, DelphiScript (a subset of Object Pascal), C++Script or
C#Script (both based on the JScript engine). All languages are restricted to variables of the OleVariant
compatible type, and cannot use pointers. Types specified in variable or function declarations are ignored.
DelphiScript support is built into TestComplete. VBScript and JScript are supported by DLLs (of the same
name) shipped with Windows and Internet Explorer. Since C++Script and C#Script are based on JScript, they
also depend on these DLLs. To run VBScript, JScript, C++Script or C#Script in TestComplete, Internet
Explorer 5.0 or higher must be installed on the machine. If you do not have the required version of Internet
Explorer, you can install the Microsoft scripting components directly. The latest version of these DLLs (as a
part of Windows Script Components) is available at http://www.microsoft.com/downloads.
For debugging VBScript, JScript, C++Script and C#Script routines, you must have either Microsoft Visual
InterDev or Microsoft Script Debugger installed. Microsoft Script Debugger is free and can be downloaded
from http://www.microsoft.com/downloads. Debugging of DelphiScript routines does not require any
additional software.
TestComplete is equally oriented on each of the supported scripting languages. However, each of the
languages has its pros and cons that may or may not match your specific requirements. Read the Selecting a
Scripting Language topic to decide what language you should choose.
For complete information on the supported scripting languages, use the links below:
¾ VBScript http://msdn.microsoft.com/en-us/library/ms950396.aspx
¾ JScript http://msdn.microsoft.com/en-us/library/ms950396.aspx
¾ DelphiScript DelphiScript Description in TestComplete help
¾ C++Script Writing C++ Scripts in TestComplete help
¾ C#Script Writing C# Scripts in TestComplete help

Scripts and Connected and Self-Testing Applications


Everything that can be done in a script can also be done in application code, using TestComplete’s Connected
Application facility. Such connected code is free from the limitations of scripting languages, and has the same
access to application internals as ordinary application code. It can also be debugged by the development tool’s
debugger, just like the rest of the application’s source.
Connected code can be written directly in the application’s source editor. However, it can also be read from
TestComplete’s project source and copied to the application source. VBScript can be read by the Visual Basic
compiler or interpreter; DelphiScript code - by Delphi; C++ code can be read by any C++ compiler, but the
necessary library to make a Connected Application is compiler-specific, and only Microsoft Visual C++ and
Borland C++Builder are supported. C#Script code can be read by any C# compiler, but to make a C#
Connected or a Self-Testing Application, you will have to add certain assemblies to the application.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


76 Scripting

Script File Format and Source Control Systems


TestComplete’s script files can have either ANSI, UTF-8 or Unicode (UTF-16) format. Some source control
systems treat Unicode files as binary and thus do not let you perform some operations over such files, for
example, compare or merge. Please refer to the documentation on your source control system to learn how you
can work with Unicode files.
To solve the problem, you can also change the character encoding format used in your project for script files.
For more information on this, see Character Encoding in TestComplete help.

Selecting the Scripting Language


The scripting language for the project is specified at the project creation time and cannot be changed later.
TestComplete supports the five languages: VBScript, JScript, Delphi, C++Script and C#Script. The languages
are quite different, so you may ask “Which one should I choose for my project?”
First of all, we would like to note that the scripting language does not depend on your tested application’s
programming language. For instance, you can use JScript to test Visual C++ applications, or VBScript to test
Delphi programs. There is only one recommendation: if you plan to create a Connected or a Self-Testing
Application, you should select the scripting language that matches the development tool where you will create
that application. That is, if you use Visual C++ or C++Builder, you should select C++Script; if you use Visual
Basic, select VBScript; if you use C#, use C#Script, and if your using Delphi, select DelphiScript. This will
make it easier to import recorded scripts to Connected and Self-Testing Applications.
The vast majority of TestComplete features is equally oriented on each of the five supported languages. So,
you can select the language that is closer to your development skills. This will decrease the test creation time,
since you will not have to learn a new language.
You will not be limited in functionality if you prefer one language to another - you will be able to use all of
TestComplete’s features regardless of which language you choose. However, due to the fact that languages
have different syntax and work via different engines, there are few exceptions:
• The size of a DelphiScript unit in a TestComplete cannot exceed 1 MB. There is no such a
limitation for projects created in other scripting languages (VBScript, JScript, C++Script and
C#Script).
• JScript does not support functions that obtain parameters by reference. The same applies to
C++Script and C#Script since these languages work via the JScript engine.
• Any of the supported scripting languages let you call routines and variables defined in another
unit. However, circular references between units are supported in VBScript and DelphiScript only
and are not supported in JScript, C++Script and C#Script.
• JScript, C++Script and C#Script may handle exceptions incorrectly when the try{} block holds
calls to routines defined in other units. That is, the try... catch... finally block works
correctly only when it does not hold calls to routines from other units.
• Some users consider that exception handling in JScript, C++Script, C#Script or DelphiScript may
be more convenient than exception handling in VBScript.
• The format of arrays in JScript, C++Script and C#Script differs from the DelphiScript and
VBScript (see Supported Scripting Languages - Peculiarities of Usage). This affects the usage of

www.automatedqa.com TestComplete by AutomatedQA Corporation


Writing Scripts – Quick Start 77

some routines (for example, the Find and FindAll methods) in JScript, C++Script and C#Script
code. For more information, see documentation for the specific method.
For information on usage peculiarities of supported scripting languages, see Supported Scripting Languages -
Peculiarities of Usage.
One more criterion that may affect the selections of the scripting language is the set of predefined language
functions. Each scripting language provides a number of built-in functions that help you perform some routine
actions, such as converting numerical values to strings and vice versa (C++Script and C#Script have the same
functions as JScript, since these languages are based on JScript). Normally, the sets of predefined functions of
different scripting languages are similar to each other, with few exceptions (for instance, DelphiScript does not
have an analogue of VBScript’s split function). However, the difference in predefined functions is
negligible, since most of predefined functions are simple and you can easily create their analogues in another
language.

Writing Scripts – Quick Start


This topic is a starting point in understanding of how to write scripts. It provides brief information on how to
perform common actions in scripts and gives you links to more detailed descriptions.
Note: We recommend that you read Writing Scripts – Overview before you proceed.

General Notes
To write scripts, you must add the Script project item to your project. You can do this at the time of the project
creation or any time later using TestComplete’s dialogs. For more information, see Adding and Removing
Project Items and Their Child Elements in TestComplete help.
A script is a routine written in one of the supported scripting languages. Script routines are organized in units
that are shown as child nodes of the Script project item in the Project Explorer panel.
The unit name can be used in script code, so the unit name should be a valid script identifier and it should not
coincide with the name of an existing programming object. If the unit name does not match these rules, you
have to rename the unit. You can do this the same way you rename any other project items. See Renaming
Projects, Project Suites and Project Items.
You can call script routines defined in one unit from another unit. You can also import units created in other
projects into your project.
To modify the code of a unit, right-click this unit in the Project Explorer and choose Edit from the context
menu. TestComplete will open the Code Editor with the unit’s code in the Workspace panel.
The Code Editor offers an abundance of features for editing script code: syntax highlighting, code completion,
code templates, outlining, bookmarks, etc. To debug the script code, you can use conditional breakpoints,
evaluate and watch dialogs and some other means provided by TestComplete. For more information on editing
and debugging capabilities, see About Code Editor and Debugging Scripts in TestComplete help.

Running Tested Applications


Each TestComplete project has a list of tested applications. This is a way for you to keep track of which
applications the project deals with, and for TestComplete to launch the applications on the list automatically
(you can uncheck any application you do not want to be launched automatically). To ensure that the tested

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


78 Scripting

applications are running before you perform any action on them, add the following code at the beginning of
your script:
[VBScript]
TestedApps.RunAll

[JScript]
TestedApps.RunAll();

[DelphiScript]
TestedApps.RunAll();

[C++Script, C#Script]
TestedApps.RunAll

To run a single tested application, use the TestedApps.Items(Index).Run statement (the Index parameter
specifies the index of the desired application in the tested applications list of your project). The following code
demonstrates how to run one instance of the first tested application in the list:
[VBScript]
TestedApps.Items(0).Run(1)

[JScript]
TestedApps.Items(0).Run(1);

[DelphiScript]
TestedApps.Items[0].Run(1);

[C++Script, C#Script]
TestedApps["Items"](0)["Run"](1);

Using the Run method you can launch one or more application instances. Also, using the method’s Timeout
parameter you can specify the number of milliseconds to wait until all application instances have been
launched. For more information, see the method description in TestComplete help.
For more information on tested applications, see Tested Applications and Working With Tested Applications
From Scripts in TestComplete help.

Addressing Processes, Windows and Controls


Before you simulate a user action over a window or control, you should obtain a program object that provides
scripting interface to that window (control). To do this, you should first obtain a process, to which the desired
window belongs (in TestComplete object model, processes are children of the System (Sys object), windows
are children of processes).
If you started a tested application by calling the Run method of the TestedApp object in your script code, then
the method will return the process object corresponding to the launched application:
[VBScript]

www.automatedqa.com TestComplete by AutomatedQA Corporation


Writing Scripts – Quick Start 79

Set p = TestedApps.Items(0).Run(1)

[JScript]
var p;
p = TestedApps.Items(0).Run(1);

[DelphiScript]
var
p : OleVariant;
begin
p := TestedApps.Items[0].Run(1);
end;

[C++Script, C#Script]
var p;
p = TestedApps["Items"](0)["Run"](1);

To obtain a scripting interface to any process running in the system (including those processes that were started
from TestComplete), use the Sys.Process or Sys.WaitProcess methods. They return a process object
that provides scripting interface to the process specified by its name and index. The index is used to distinguish
several instances of the same application. If there is only one instance of the application running, the index can
be omitted. Below is the typical code for obtaining the process object that provides a scripting interface for the
Notepad application:
[VBScript]
Set p = Sys.Process("Notepad")

[JScript]
p = Sys.Process("Notepad")

[DelphiScript]
var
p : OleVariant;
begin
p := Sys.Process('Notepad');

end;

[C++Script, C#Script]
var p;
p = Sys["Process"]("Notepad")

If the specified process does not exist, the Process method will post an error message to the test log and return
an empty stub object containing only one property named Exists. If you then attempt to call any other
methods or properties using this stub object, TestComplete will either post an error message to the test log or
display an error message on screen. The action to be performed is specified by the When referring to a
non-existent object that can be changed in the Engines – General Options dialog. To invoke this dialog,
choose Tools | Options from TestComplete’s main menu and then select Engines | General on the left of the
ensuing Options dialog.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


80 Scripting

To wait until the desired process starts up, you can use the WaitProcess method. This method pauses the
script execution until the specified process is created or the specified timeout is over. If the process is not
created, the method does not post an error message to the log, it just returns an empty object:
[VBScript]
Set p = Sys.WaitProcess("Notepad", 2000)
If Not p.Exists Then
' Process does not exist
End If

[JScript]
p = Sys.WaitProcess("Notepad", 2000)
if (! p.Exists)
// Process does not exist
...

[DelphiScript]
var
p : OleVariant;
begin
p := Sys.WaitProcess('Notepad', 2000);
if not p.Exists then
// Process does not exist
...
end;

[C++Script, C#Script]
var p;
p = Sys["Process"]("Notepad", 2000)
if (! p["Exists"])
// Process does not exist
...

A possible alternative to the WaitProcess method is to specify the wait time using the Timeout parameter of
the TestedApp.Run method.

After you have the process, you can obtain windows belonging to this process. The way you do this depends on
whether your application is compiled as an Open Application or not. Open Applications provide
TestComplete with access to their internal objects, methods and properties. .NET, Java, WPF and Visual Basic
6.0 applications are always “open” to TestComplete. Visual C++, Delphi and C++Builder applications need to
be recompiled in a special manner. For complete information on this, see Open Applications in TestComplete
help.
If your application is an Open Application, you can address windows using one of the following special
methods:
Method Description
WinFormsObject Provides access to windows in Microsoft .NET applications by object name or by
control class name, window text (caption) and index.
VCLNETObject Provides access to windows in Borland VCL.NET applications by object name or

www.automatedqa.com TestComplete by AutomatedQA Corporation


Writing Scripts – Quick Start 81

by control class name, window text (caption) and index.


VBObject Provides access to windows in Visual Basic 6.0 applications by object name.
VCLObject Provides access to windows in Delphi and C++Builder VCL Open Applications
by object name.
CLXObject Provides access to windows in Delphi and C++Builder CLX Open Applications
by object name.
SwingObject Provides access to windows in Java Swing applications by object name or by class
name, caption and index.

AWTObject Provides access to windows in Java AWT applications by object name or by class
name, caption and index.
SWTObject Provides access to windows in Java SWT applications by object name or by class
name, caption and index.
WFCObject Provides access to windows in Java WFC applications by object name or by class
name, caption and index.
WPFObject Provides access to windows in WPF (XAML) applications by object name.
Windows and objects of Visual C++ applications as well as windows and objects of Java applications that were
built using other libraries than Swing and AWT, are addressed as windows of black-box applications (see
below).
The following example demonstrates how you can obtain a form of a .NET application created with Microsoft
Windows Forms library. If your Open Application was created with another development tool, then to obtain a
form of your application replace calls to the WinFormsObject method with calls to the appropriate method
from the table above.
[VBScript]
Set p1 = Sys.Process("MyApp")
Set w1 = p1.WinFormsObject("MainForm")

[JScript]
p1 = Sys.Process("MyApp");
w1 = p1.WinFormsObject("MainForm");

[DelphiScript]
var
p1, w1 : OleVariant;
begin
p1 := Sys.Process('MyApp');
w1 := p1.WinFormsObject('MainForm');
end;

[C++Script, C#Script]
var p1, w1; p1 = Sys["Process"]("MyApp");
w1 = p1["WinFormsObject"]("MainForm")

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


82 Scripting

Note: Each of the changed methods returns the wrapper object for a window of a tested application.
This wrapper object provides access to the methods and properties defined by the application
code (for example, methods and properties of .NET, Java or MFC classes) as well as methods,
properties and actions provided by TestComplete.
It is possible that a process contains several windows having the same name (for instance, your Open
Application may create several instances of the EditOrder form). To distinguish such windows in your scripts,
you can use any of the following alternatives:
• Use the Name Mapping feature (see Name Mapping in TestComplete help).
• Find for the window using the Find or FindId method of the process (Find returns a child object
by values of its properties, FindId returns a child object by its id).
• Enumerate all of the windows belonging to the same process, examine the window properties (or
properties of their child windows) and obtain the desired window. To enumerate windows, you
can use the Child and ChildCount properties of the process object.
If a window has no Name property (for example, windows of Visual C++ applications have no names), or if
your application is not an Open Application, you can use the Window and WaitWindow methods of the
process object to get the desired window. These methods return a top-level window of a process using
window class name, caption and index as parameters:
[VBScript]
Set p1 = Sys.Process("MyApp")
Set w1 = p1.Window("WindowClassName", "WindowCaption", 1)
' or
Set w1 = p1.WaitWindow("WindowClassName", "WindowCaption", 1, 2000)

[JScript]
p1 = Sys.Process("MyApp");
w1 = p1.Window("WindowClassName", "WindowCaption", 1);
// or
w1 = p1.WaitWindow("WindowClassName", "WindowCaption", 1, 2000);

[DelphiScript]
var
p1, w1 : OleVariant;
begin
p1 := Sys.Process('MyApp');
w1 := p1.Window('WindowClassName', 'WindowCaption', 1);
// or
w1 := p1.WaitWindow('WindowClassName', 'WindowCaption', 2000);
end;

[C++Script, C#Script]
var p1, w1; p1 = Sys["Process"]("MyApp");
w1 = p1["Window"]("WindowClassName", "WindowCaption", 1);
// or
w1 = p1["WaitWindow"]("WindowClassName", "WindowCaption", 1);

www.automatedqa.com TestComplete by AutomatedQA Corporation


Writing Scripts – Quick Start 83

The differences between the Window and WaitWindow methods are similar to the differences between the
Sys.Process and Sys.WaitProcess methods. Window checks whether the specified window exists and if
it does not, the method posts an error message to the test log. WaitWindow delays the script execution until the
specified window is created or until the specified timeout is over. It does not post an error message to the log if
the desired window does not exist.
If the window with the specified attributes does not exist, both Window and WaitWindow methods will return
an empty stub object containing only one Exists property. If you attempt them to call any other method or
property for the stub object, TestComplete will either post an error message to the test log or show an error
message on screen. Which actions are performed is specified by the When referring to a non-existent object
option, described above.
To determine which class name, caption or index to use to address a window, explore your application in the
Object Browser. You can copy the whole window recognition string from the Object Browser:

Note: You can use wildcards (? and *) when specifying the window caption and class name.
The Window and WaitWindow methods of the process object return the window program object that
corresponds to a top-level window of a process. To get a child window or control, call Window or
WaitWindow methods of that window object.

If your application is an Open Application, you can obtain child windows by their names or by using the
methods described above (WinFormsObject, VBObject and others).
[VBScript]
Set p1 = Sys.Process("MyApp")
Set w1 = p1.WinFormsObject("MainForm")
Set w2 = w1.WinFormsObject("Button1") ' or Set w2 = w1.Button1

[JScript]
p1 = Sys.Process("MyApp");
w1 = p1.WinFormsObject("MainForm");
w2 = w1.WinFormsObject("Button1"); // w2 = w2.Button1;

[DelphiScript]
var
p1, w1, w2 : OleVariant;
begin
p1 := Sys.Process('MyApp');
w1 := p1.WinFormsObject('MainForm');
w2 := w1.WinFormsObject('Button1'); // w2 := w1.Button1;
end;

[C++Script, C#Script]

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


84 Scripting

var p1, w1, w2; p1 = Sys["Process"]("MyApp");


w1 = p1["WinFormsObject"]("MainForm");
w1 = w1["WinFormsObject"]("Button1"); // or w2 = w1["Button1"];

If you do not call any special xxxxObject methods, TestComplete will return the wrapper object for the
requested window (or control) that will hold only the application-defined properties. For instance, if you are
testing a .NET application, the wrapper object only holds the methods and properties of .NET classes. To
obtain an object containing both application-defined and TestComplete methods and properties, use the
WinFormsObject method (or one of other special methods mentioned above).

The hierarchy of windows depends on the Object tree model option of your TestComplete
project. To view or change it, open the project editor, switch to the Properties page and select
the General cateogry on the left of the page. The option will be on the right of the page. This
option specifies which of the object tree models, Flat or Tree, is active. For complete
information on them, see Object Tree Models in TestComplete help. Note that scripts created
for the Flat model are not supported by the Tree model and vice versa. That is, if you run a
script routine created for the Flat model when the Tree model is active, TestComplete will not
find windows and will post errors to the test log.
To check the state of the Object tree model option in scripts, use the
Options.Project.General.TreeModel property.

Note: The child objects list of some objects can change dynamically (for instance, windows can be
created or deleted within the process). TestComplete automatically updates the child list when
you obtain a child of some object. You can force TestComplete to update the child list of an
object by calling the Refresh method of that object.
If the same parent window contains two or more objects having the same name, then to obtain the desired
window, you can use approaches similar to those that were described for top-level windows (name mapping,
searching with Find and FindId method, enumeration of child windows).
Once you obtain the window object for the desired window or control, you can use the object’s methods and
properties to work with this window (or control) as your needs dictate. For instance, you can simulate user
actions (mouse clicks or keystrokes), maximize or minimize a window (if it is a top-level or MDI window),
change window properties (for example, text) and perform other actions. To determine what properties are
available to your TestComplete scripts, we would recommend to look up the window properties in the Object
Browser.
If your application in an Open Application (for example, a .NET application), the Object Browser will show
methods and properties of .NET classes as well as methods and properties provided by TestComplete.
Note that TestComplete automatically determines the type of a window (button, list box, tree view and so on).
It adds specific methods and properties to the window object, so you can use these methods and properties to
perform actions specific to the control. For instance, you can enumerate nodes of a tree view, click items of a
list view control, get combo box items and so on.
To determine the control type TestComplete checks the window class name. For instance, if the class name of
a window coincides with the default class name given by Windows to button windows, TestComplete
considers a window as a button. Similarly TestComplete determines the types of other controls (list boxes, tree
views, etc.)
Of course, the class name of a window may differ from the default class name. In this case TestComplete uses
Object Mapping settings to determine the control type. To view or change these settings, open the project

www.automatedqa.com TestComplete by AutomatedQA Corporation


Writing Scripts – Quick Start 85

editor, activate the Properties page and choose the Object Mapping category on the left of the page.
TestComplete will display the settings on the right of the page.
For complete information on how to address processes, windows and controls in scripts, see How
TestComplete Recognizes Processes, Windows and Controls in TestComplete help.

Simulating User Actions


TestComplete includes all the means for simulating user actions. You can --
• Maximize, minimize, bring to front and change position of application’s top-level windows on the
screen.
• Simulate mouse clicks, double-clicks, drag-and-drop events, keystrokes, etc. in controls on
application forms.
• Simulate selection of menu and toolbar items.
• Simulate selection of items in list view, tree view, list box and many other controls.
For instance, to simulate a click of a button, obtain the window object for that button and then call the
ClickButton method of this object (TestComplete automatically adds this method to all window objects that
correspond to buttons):
[VBScript]
Set p1 = Sys.Process("notepad")
Set w1 = p1.Window("#32770", "Open", 0)
Set w2 = w1.Window("Button", "&Open", 1)
w2.ClickButton

[JScript]
p1 = Sys.Process("notepad");
w1 = p1.Window("#32770", "Open", 0);
w2 = w1.Window("Button", "&Open", 1);
w2.ClickButton();

[DelphiScript]
var
p1, w1, w2 : OleVariant;
begin
p1 := Sys.Process('notepad');
w1 := p1.Window("#32770", "Open", 0);
w2 := w1.Window("Button", "&Open", 1);
w2.ClickButton();
end;

[C++Script, C#Script]
var p1, w1, w2;
p1 = Sys["Process"]("notepad");
w1 = p1["Window"]("#32770", "Open", 0);
w2 = w1["Window"]("Button", "&Open", 1);
w2["ClickButton"]();

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


86 Scripting

TestComplete automatically determines the window type by the window’s class name (see the previous
section) and adds type-specific methods and properties to the window object that corresponds to that window.
You can call these methods and properties to perform operations specific to the control, for instance, if a
window is a tree view control, you can use specific methods to simulate clicks and double-clicks over tree view
nodes. TestComplete provides extended support for almost all types of standard controls (see Working With
Win32 Controls in TestComplete help). Besides, TestComplete supports recent Windows Presentation
Foundation, .NET and Java controls, as well as a number of popular third-party components. Furthermore,
using object mapping, you can set up TestComplete so it handles a custom control as if it is a standard one. See
Working With Custom Controls in TestComplete help.
It is possible that an object will contain several methods or properties with the same name. For instance, an
object of an Open Application may contain the method Click and TestComplete may add a method of the
same name to this object. If you then call the Click method of this object in your scripts, the script engine will
use the method provided by TestComplete, not the method defined in your application. To call the latter, use
the appropriate namespace: NativeClrObject, NativeVBObject, NativeCPPObject or another. For
detailed information on namespaces and how to use them, see Using Namespaces in TestComplete help.
For complete information on simulating user actions, see Simulating User Actions in TestComplete help.

Retrieving Data From Application Objects, Windows and Controls


TestComplete automatically determines the type of a control (buttons, tree view, list box, etc.) and adds
specific methods and properties to the window object corresponding to this control (see the Addressing
Processes, Windows and Controls section above). Using these methods and properties you can obtain data held
in the desired controls.
If TestComplete cannot associate the control used with any standard Win32 control, then you can try
compiling your application as an Open Application. Open Applications provide access to their internal
objects, methods and properties, and using these methods and properties you should be able to obtain data
stored in the desired control.
Note: An object may contain several properties having the same name (for instance, an object of
an Open Application may contain the property Left and TestComplete may add a property
of the same name to the object). If you address the Left property of this object in your
scripts, TestComplete will use its property, not the property defined in your application. To
call the latter, use namespaces.
For complete information on how to obtain data from windows and controls, please see Retrieving Data From
Application Objects, Windows and Controls in TestComplete help You may also find the Working With Grids
topic helpful.

Posting Messages to the Test Log


To post messages to the test log, use methods of the Log object. Using these methods you can post messages of
different types (error, warning, informative and other). The following code snippet posts error, warning and
informative messages to the log:
[VBScript]
Log.Error "Message Text 1", "Extended Message Text 1"
Log.Warning "Message Text 2", "Extended Message Text 2 "
Log.Message "Message Text 3", "Extended Message Text 3 "

www.automatedqa.com TestComplete by AutomatedQA Corporation


Writing Scripts – Quick Start 87

[JScript]
Log.Error("Message Text 1", "Extended Message Text 1");
Log.Warning("Message Text 2", "Extended Message Text 2");
Log.Message("Message Text 3", "Extended Message Text 3 ");

[DelphiScript]
Log.Error('Message Text 1', 'Extended Message Text 1');
Log.Warning('Message Text 2', 'Extended Message Text 2');
Log.Message('Message Text 3', 'Extended Message Text 3');

[C++Script, C#Script]
Log["Error"]("Message Text 1", "Extended Message Text 1");
Log["Warning"]("Message Text 2", "Extended Message Text 2");
Log["Message"]("Message Text 3", "Extended Message Text 3");

Each message can have an image that is posted with it. The message parameters let you specify color and font
style of a message. Besides messages of various types, you can also post images and file links (see methods of
the Log object). The Log object also includes special methods that let you organize log messages into folders.
For complete information on posting messages and images to the log, see Posting Messages to the Log in
TestComplete help.

Database Access
To work with databases directly from your scripts, use TestComplete’s ADO and BDE program objects.
Using the ADO object you can work with databases via Microsoft ADO objects, methods, and properties. The
BDE object lets you work with databases via wrappers of VCL data-aware objects for BDE access.

An alternative to using ADO and BDE, is the creation of ADO objects as COM objects from scripts:
[VBScript]
Set AConnection = CreateObject("ADODB.Connection")
' Specify the connection string
AConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.3.51;" + _
"Data Source=C:\Microsoft Visual Studio\VB98\biblio.mdb"
' Activate the connection
AConnection.Open

[JScript]
AConnection = new ActiveXObject("ADODB.Connection");
// Specify the connection string
AConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.3.51;" +
"Data Source=C:\\Microsoft Visual Studio\\VB98\\Biblio.mdb";
// Activate the connection
AConnection.Open();

[DelphiScript]

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


88 Scripting

var
AConnection : OleVariant;
begin
AConnection := Sys.OleObject('ADODB.Connection');
// Specify the connection string
AConnection.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.3.51;' +
'Data Source=C:\Microsoft Visual Studio\VB98\biblio.mdb';
// Activate the connection
AConnection.Open;

end;

[C++Script, C#Script]
var AConnection;
AConnection = Sys["OleObject"]("ADODB.Connection");
// Specify the connection string
AConnection["ConnectionString"] = "Provider=Microsoft.Jet.OLEDB.3.51;" +
"Data Source=C:\\Microsoft Visual Studio\\VB98\\Biblio.mdb";
// Activate the connection
AConnection["Open"]();

For more information on database access from scripts and for code examples, see Working With Databases in
TestComplete help.

Calling Project Elements from Scripts


For each project item TestComplete provides special program objects that let you work with project items from
scripts. For instance, these objects let you execute tests provided by project items, or get project items' property
values.
You can address project elements from scripts using the element name as it is shown in the Project Explorer
panel. For instance, to execute a low-level procedure from a script, you can use the following code:
LLPCollection1.LLP1.Execute()

Here LLPCollection1 is the name of the Low-Level Procedures Collection project item as it is shown in the
Project Explorer. LLP1 is the name of the desired low-level procedure.
Similarly, you can initiate execution of tests provided by other project items (HTTP Load Testing, Manual
Testing, Unit Testing, etc.) For more information on how to do this, see the description of the appropriate
project item in TestComplete help.

How TestComplete Recognizes Processes, Windows and


Controls
This topic explains how object names are formed. This is important information, since these names are
returned by the Name property and are used to address objects in your scripts. The topic includes the following
sections:

www.automatedqa.com TestComplete by AutomatedQA Corporation


How TestComplete Recognizes Processes, Windows and Controls 89

¾ Naming Concepts
¾ Processes
¾ Window Objects
¾ Controls and Objects Within Applications
¾ Web Objects

Naming Concepts
To address objects of tested applications in scripts, TestComplete uses properties of these objects. Each object
has a number of properties such as “class name”, “text”, “enabled” and so on. You can view available object
properties in the Object Browser or using the Object Properties window.
Some object properties are often changed during the application's execution (for instance, text in an edit box),
while others (for instance, window handle) remain constant but may change between two application runs.
Other properties (for instance, window class name in some applications) do not change between application
runs.
In order for a property to be used in addressing an object from a script, it must uniquely distinguish the desired
object from other similar objects and remain unchanged during the application's execution and between
application runs. Also, it is desirable for the property to be readable.
In a general case, no property meets all of these requirements, so TestComplete uses a combination of
properties to identify objects. For instance, to address processes it uses the name of the executable file that
started the process and the process index; to address windows it uses the window's class name, window's
caption and index. In other words, the object names typically include several components:

For complete information on the naming process, windows and other objects of tested application, see the next
sections of this topic.
Some components of an object’s name (for instance, window caption or process index)
can change during the application run, so it is possible that you will have to use
different names to address the same process or window during the script run.
Using the Name Mapping feature you can redefine the combination of properties TestComplete uses to address
objects. For more information on this, see Name Mapping in TestComplete help.
The addressing is hierarchical. For instance, to obtain a program object corresponding to a window, you should
first obtain a process object; to get program access to a control, you should first obtain a window object that
corresponds to the window containing the desired control, and so on. To explore the hierarchy of objects, use
the Object Browser.
The object name used by TestComplete to address an object is specified by the object’s Name property. This
property belongs to every program object that provides a scripting interface to a process, window or control of
a tested application. Besides Name, these objects also contain the FullName property, which in addition to the
object name also includes the names of parent objects. In fact, FullName returns a string that identifies the
object in the system.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


90 Scripting

When recording a script, TestComplete addresses the objects using the name shown in the Object Browser.
However, if you create a custom name for the object using the Name Mapping feature, TestComplete will use
the mapped name or alias.
The following sections of this topic provide detailed information on addressing processes, windows and
controls of the tested applications.

Processes
To work with processes from scripts, use the process objects. To obtain a process object, call the
Sys.Process or Sys.WaitProcess methods. These methods use parameters that uniquely identify the
process in the operating system:
• The name of an executable file that starts the process. The file name is used without an extension.
• The index of a process instance. There can be several running applications with the same name in
the system. In this case, the process index is used to distinguish one process instance from another.
The first started process has index 1, the second - 2, etc.
[VBScript, Visual Basic]
' Obtains the object that provides scripting interface
' to the second instance of Notepad
Set p = Sys.Process("Notepad", 2)
[JScript]
// Obtains the object that provides scripting interface
// to the second instance of Notepad
var p = Sys.Process("Notepad", 2);
[DelphiScript, Delphi]
var
p : OleVariant;
begin
// Obtains the object that provides scripting interface
// to the second instance of Notepad
p := Sys.Process('Notepad', 2);
end;
[C++Script, C#Script, C++, C#]
var p;
// Obtains the object that provides scripting interface
// to the second instance of Notepad
p = Sys["Process"]("Notepad", 2);

Note that the process index can change during the script run: if a process with a lower index is terminated, the
higher indexes will be decreased, so the names of other processes are changed.
If you omit the process index when referring to the process, the default value 1 will be used, for example, the
names Process("Notepad") and Process("Notepad", 1) are equivalent.

www.automatedqa.com TestComplete by AutomatedQA Corporation


How TestComplete Recognizes Processes, Windows and Controls 91

Window Objects
The principles which TestComplete uses to recognize windows depend on whether the application under test is
an Open Application (white-box) or non-Open Application (ordinary, black-box).

Open Applications
If the tested application was compiled as an Open Application, you can address its windows and objects using
special methods provided by TestComplete: WinFormsObject, VBObject, VCLObject, SwingObject, and
so on. These methods let you address the desired window by using the value specified by the application’s
Name property, or by using the class name, caption and index. The method used depends on the programming
language and the development tools used to create your application. For complete information on using these
methods, see the following topic in TestComplete help:

¾ Addressing Windows, Controls and Objects of Open Applications

Black-Box Applications
To address windows in black-box applications, TestComplete by default uses the following window attributes:
• Window class name
• Window caption
• Window index
The Windows API offers several attributes meant to distinguish one window from the other, among those
currently open in the system. The one it uses internally, the handle, is changed from one application to the next
and, therefore, is useless. The attributes used by TestComplete - class name, caption and index - are more
stable. The use of other properties (for example, control id) is also possible. See below for more information.
Now we will describe attributes used by default.
• Window class name. This attribute specifies the name of the window’s class as it is registered in
the operating system, for instance, msctrl_statusbar32, #32770, TForm1 or
Afx:400000:b:10008:6:1027b.
Window class name is the most stable component of a window name. It does not change during the
script run. However, it is not unique for a window (it is quite possible that two or more windows
have the same name) and it can change from one application run to another (these changes are
typical for MFC applications). To negate the change of the class name, you can replace the varying
parts of the class name with wildcard symbols (“*” and “?”). For instance, you can use
“Afx:400000:b:*” instead of “Afx:400000:b:10008:6:1027b”. Without the wildcards, you would
have to modify window class names in script code before each run. To specify an asterisk as part
of the window class name, use two consequent asterisks.
• Window caption. The window caption identifies the window for users. It is not unique and there
can be two windows with the same caption in the system. Generally, the caption can also be
changed during the execution of the application. The developer may use it to display any helpful
information, for instance, the caption of a text editor usually displays the name of the edited
document: “MyEditor - Document1.rtf”.
You can use wildcard symbols (“*” and “?”) to specify caption patterns. This technique makes
application testing more flexible. For example, you can specify only the constant part of the

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


92 Scripting

caption (“MyEditor - ”), and replace the name of the edited document with “*”. In this case, the
window caption does not depend on the name of the edited document. If an asterisk is part of the
caption, then to specify it, use duplicated asterisks (for example, the string “MyEditor -
DocName.txt**” corresponds to the caption “MyEditor - DocName.txt*”).
The titles of main windows often contain the application’s name followed by a hyphen and the
name of the active window (or document, project, file and so on). TestComplete’s recorder will
automatically record the string “*” for any caption that includes a hyphen. Thus, “GraphEditor -
MyPicture1.bmp” is recorded as “*”.
Note that many windows, especially smaller ones, have no caption, that is, they all have the same
caption, empty. Menus for instance, are captionless windows, and they are rather typical. Entire
window classes are used without captions, making the caption useless to distinguish among
siblings. In this case, to obtain a window, you should use other attributes: class name and index.
• Index. The window’s index is more unstable than the window’s caption, but it is needed when a
process or parent window has several child windows with the same caption and the same class
name. The index is the current front-to-back onscreen position (similar to Z-order) of the window
among windows of the same class with the same parent. Index 1 corresponds to the currently
topmost window relative to other windows that have the same class name. The window index is
determined by certain Windows API functions, so even if two or more windows visually have the
same Z-order, they have different window indexes. To determine the index of the desired window,
explore the application windows and controls in TestComplete’s Object Browser.
The index of an application window changes when other windows from the class are called
onscreen or when the front-back position of this window changes.
TestComplete may not record a window’s index when you are recording a script, if the class name
and caption provide enough information for the recognition of this window.
To obtain a window in a script, you can use one of the following methods: Process.Window,
Process.WaitWindow, Window.Window and Window.WaitWindow. These methods use parameters that
specify the class name, caption and index of the desired window:
[VBScript, Visual Basic]
Set p = Sys.Process("winword")
Set w = p.Window("OpusApp", "Microsoft Word - *", 1)
[JScript]
p = Sys.Process("winword");
w = p.Window("OpusApp", "Microsoft Word - *", 1)
[DelphiScript, Delphi]
var
p, w : OleVariant;
begin
p := Sys.Process('winword');
w := p.Window('OpusApp', 'Microsoft Word - *', 1)
end;
[C++Script, C#Script, C++, C#]
var p, w;
p = Sys["Process"]("winword");
w = p.["Window"]("OpusApp", "Microsoft Word - *, 1")

www.automatedqa.com TestComplete by AutomatedQA Corporation


How TestComplete Recognizes Processes, Windows and Controls 93

The hierarchy of windows depends on the Object tree model option of your TestComplete
project. This option specifies the active object model: Flat or Tree. For complete information, see
Object Tree Models in TestComplete help. We recommend to read this topic since knowing the
tree model is essential for running the scripts. Scripts created for the Flat model will run
incorrectly if the Tree model is active and vice versa.
To check the state of the Object tree model option in scripts, use the
Options.Project.General.TreeModel property.

In order to identify windows you can use not only the mentioned attributes (class name, caption and index), but
also other window attributes. For example, you can use the control identifier of a window. This identifier is an
application-defined integer value associated with a window. The identifier value is returned by Windows API
functions: GetWindowLong(hwndCtrl, GWL_ID) or GetDlgCtrlID(hwndCtrl). We use the term
“control identifier” since this identifier is typically used to address child windows, for instance, controls on a
form (controls are also windows). However, top-level windows also have identifiers.
The control identifier can be specified by a developer (for example, when they designed the dialog template in
Visual Studio) or by the development tool itself (for instance, if the development tool does not support manual
setting of the identifier). Though the identifier seems to be a persistent window attribute, it may be unspecified
(0), its value may change from one application run to another or the program may return the same identifier for
two different windows. If you do not find the identifier helpful, you can use the window caption, class name
and index to find the desired window.

The following code uses the FindChild method that returns a window by its control identifier:
[VBScript]
Set p = Sys.Process("Notepad")
Set w = p.FindChild("ControlId", 133099, 1)
[JScript]
var p, w;

p = Sys.Process("Notepad");
w = p.FindChild("ControlId", 133099, 1);
[DelphiScript]
var
p, w;
begin
p := Sys.Process('Notepad');
w := p.FindChild('ControlId', 133099, 1);
end;
[C++Script, C#Script]
var p, w;

p = Sys["Process"]("Notepad");
w = p["FindChild"]("ControlId", 133099, 1);

The FindChild method returns a child object by any combination of its property values. For instance, the
method can find a window using a combination of the ChildCount, Visible, WndClass and WndStyle
properties (or any other set of properties that let you uniquely distinguish the window). The combination of
properties that let you uniquely identify the window depends on the application under test. For instance, two

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


94 Scripting

forms may have different window styles (WndStyle property) and different number of child windows
(ChildCount property). Using the FindChild method you can obtain the desired object using any
combination of its properties. For more information on using the method, see the method description in
TestComplete help.

To obtain a window by custom property values, you can also use the Name Mapping feature. Name
mapping lets you visually specify the combination and values of the properties that will be used for
recognition and to assign custom names to objects that will match the specified recognition criteria.
Once you map an object, you can address this object in scripts using the mapped name, rather than the
object’s default name. For more information, see Name Mapping in TestComplete help.

Controls and Objects within Applications


Addressing controls is similar to addressing windows, since for the operating system each control is a window.
Like addressing windows, addressing controls and objects depend on whether the tested application is
compiled as an Open Application or not.

Open Applications
For information on how to address controls and objects in Open Applications, see following topic in
TestComplete help:

¾ Addressing Windows, Controls and Objects of Open Applications

Black-Box Applications
TestComplete recognizes controls on forms of black-box applications using attributes of window objects: class
name, caption and index. To obtain controls, you use the window objects, which are returned by Window or
WaitWindow methods of the parent window object. These methods use the recognition attributes that were
explained in the previous section: window class name, window caption and index --
[VBScript, Visual Basic]
Set p = Sys.Process("MyApp")
Set w = p.Window("WndClass", "WndCaption", 1) ' Obtains a top-level window
Set w2 = w.Window("ControlWndClass", "ControlText", 1) ' Obtains a control on the
top-level window
[JScript]
var p, w, w2;
p = Sys.Process("MyApp");
w = p.Window("WndClass", "WndCaption", 1); // Obtains a top-level window
w2 = w.Window("ControlWndClass", "ControlText", 1); // Obtains a control on the
top-level window
[DelphiScript, Delphi]
var
p, w, w2 : OleVariant;
begin
p := Sys.Process('MyApp');
w := p.Window('WndClass', 'WndCaption', 1); // Obtains a top-level window
w2 := w.Window('ControlWndClass'. 'ControlText', 1); // Obtains a control on the
top-level window
end;

www.automatedqa.com TestComplete by AutomatedQA Corporation


How TestComplete Recognizes Processes, Windows and Controls 95

[C++Script, C#Script, C++, C#]


var p, w, w2;
p = Sys["Process"]("MyApp");
w = p["Window"]("WndClass", "WndCaption", 1); // Obtains a top-level window
w2 = w["Window"]("ControlWndClass", "ControlText", 1); // Obtains a control on the
top-level window

The methods we use in the above example address the controls using the standard recognition attributes: class
name, caption and index. Since controls are windows, you can also address the controls using any other
property (for instance, ControlId) or combination of properties. For example, the following code shows how
you can obtain a window by using the ControlId property. For code sample that searches using a
combination of properties, see the FindChild method description in TestComplete help:
[VBScript]
Set p = Sys.Process("Notepad")
Set w1 = p.Window("Notepad", "Untitled - Notepad", 1)
Set w2 = w1.FindChild("ControlId", 15, 1) ' Obtains a child window by ControlId
[JScript]
var p, w1, w2;

p = Sys.Process("Notepad");
w1 = p.Window("Notepad", "Untitled - Notepad", 1);
w2 = w1.FindChild("ControlId", 15, 1); // Obtains a child window by ControlId
[DelphiScript]
var
p, w1, w2;
begin
p := Sys.Process('Notepad');
w1 := p.Window('Notepad', 'Untitled - Notepad', 1);
w2 := w1.FindChild('ControlId', 15, 1); // Obtains a child window by ControlId
end;
[C++Script, C#Script]
var p, w1, w2;

p = Sys["Process"]("Notepad");
w1 = p["Window"]("Notepad", "Untitled - Notepad", 1);
w2 = w1["FindChild"]("ControlId", 15, 1); // Obtains a child window by ControlId

You can also assign a custom name to a control by using the Name Mapping feature.
The child objects list of process or window objects can change dynamically. For instance, windows can be
created or deleted, so the list of process’s child objects is changed. TestComplete automatically updates the
child list when you attempt to obtain a child of an object. You can force TestComplete to update the child list of
an object by calling the Refresh method of that object.

The hierarchy of windows depends on the Object tree model option of your TestComplete
project. For complete information about the supported tree models, see Object Tree Models in
TestComplete help. We recommend to read this topic since knowing the tree model is essential
for running the scripts. Scripts created for Flat model will run incorrectly if the Tree model is
active and vice versa.

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


96 Scripting

Web Objects
When testing Web pages, TestComplete works with the elements of Web pages as it would with application
objects. The names used for these objects depend on the Web Testing | Tree model project setting. It specifies
the object model (DOM, Tag, Tree or Hybrid) on the page. The objects’ names in these models are different.
For detailed information on how they are formed, see Web Tree Models in TestComplete help. You can see
the names, which TestComplete uses to address web page elements, in the Object Browser.

Calling Routines and Variables Declared in Another Unit


By default, script code can call only those routines (procedures or functions), variables and constants that
reside within the same unit. To call routines, variables or constants in another unit, the current unit must be
“linked” to it.

In VBScript projects, place the cursor at the beginning of the unit and add the following string:
[VBScript]
'USEUNIT Unit_Name

Be sure to specify the apostrophe ( ' ) before USEUNIT.


To link several units, use the following syntax:
[VBScript]
'USEUNIT Unit1_Name
'USEUNIT Unit2_Name

If you have a VBScript class defined in one unit and you want to create a class instance from another unit, then
using the USEUNIT statement is not enough. You also have to create a special routine that will return the
desired class instance. For more information, see Supported Scripting Languages - Peculiarities of Usage.

In DelphiScript projects, place the cursor at the beginning of the unit and add the following string:
[DelphiScript]
uses Unit_Name;

If you need to link several units, separate their names with commas:
[DelphiScript]
uses Unit1_Name, Unit2_Name;

In JScript, C++Script and C#Script projects place the cursor at the beginning of the unit and add the
following string:
[JScript, C++Script, C#Script]
//USEUNIT Unit_Name

Be sure to specify the double slash ( // ) before USEUNIT.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Calling Routines and Variables Declared in Another Unit 97

You can link to several units in the following manner:


[JScript, C++Script, C#Script]
//USEUNIT Unit1_Name
//USEUNIT Unit2_Name

The USEUNIT statement does not allow tab or space characters at the beginning of the line and
between the USEUNIT and the comment operator (' in VBScript and // in JScript). So, the
following use of USEUNIT will cause an error:
[VBScript]
' USEUNIT Unit_Name
'USEUNIT Unit_Name
...

[JScript, C++Script, C#Script]


// USEUNIT Unit_Name
//USEUNIT Unit_Name
...

Note: If you want to make a variable (constant) visible in other units, you need to declare this
variable (constant) outside of any routine, that is, you need to declare a global variable or
constant. Otherwise, the variable (constant) will be visible only within the routine where it is
declared.

Once an external unit is linked to the current one, all routines as well as global variables and constants of the
external unit can be called in the current unit. However, this is possible only if the current unit does not contain
a routine, a global variable or a global constant of the same name. You can work around this problem by
prefixing external calls by their unit names. That is, you can use the following syntax:
MyUnit.MyRoutine(Param1, Param2)
MyUnit.MyVariable
MyUnit.MyConstant

To call script routines located in another script unit, you can also use the Runner.CallMethod method. It
calls any routine specified by its full name (that is, unit_name.routine_name). If you call a script routine
using this function, there is no need to include the unit specified by unit_name in the uses (USEUNIT) clause
of the current unit.
Note that DelphiScript and VBScript units in TestComplete can refer to each other. In other words, circular
references are allowed. For instance, if you need to call scripts declared in UnitA from UnitB, and to call scripts
declared in UnitB from UnitA, you must add references to both units --
[VBScript]
UnitA
'USEUNIT UnitB
...
UnitB
'USEUNIT UnitA

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


98 Scripting

...

[DelphiScript]
UnitA
uses UnitB;
...
UnitB
uses UnitA;
...

Note: The circular reference is not allowed in JScript, C++Script and C#Script. Circular links in
these languages may cause errors in the jscript.dll (C++Script and C#Script are based on
JScript and also use this DLL) and these errors can cause other errors in TestComplete.

Supported Scripting Languages – Peculiarities of Usage


TestComplete supports the following scripting languages:
• VBScript
• JScript
• DelphiScript
• C++Script
• C#Script
These languages have different syntax and work via different scripting engines. Their usage has some
peculiarities described below. These are features concerning the language support in TestComplete as well as
some peculiarities, which are not well-known and can be overlooked by beginners.

Note: There is one peculiarity that is common for all supported scripting languages. It concerns the
methods’ and functions’ names.
You can skip the object name when calling methods of some program objects. For instance,
you can call the Delay method of the BuiltIn object as BuiltIn.Delay(…) or Delay(…).
By default, you can do this for methods of the BuiltIn, Utilities and Win32API objects,
but custom objects may also support this functionality.
If the method’s name coincides with the function’s name that is provided by the scripting
language engine, TestComplete will call this scripting language’s function rather than the
object’s method.
To solve the problem, put the object name before the function name.

VBScript
The usage of VBScript has the following peculiarities:
• If you assign an object to a variable or property, use the Set statement, for example:

www.automatedqa.com TestComplete by AutomatedQA Corporation


Supported Scripting Languages – Peculiarities of Usage 99

[VBScript]
Set p = Sys.Process("MyProcess") ' Correct
p = Sys.Process("MyProcess") ' Incorrect !!!

• In TestComplete, script units can refer to each other, so you can call routines and variables defined
in one unit from another unit. VBScript supports circular references between units.
• To debug VBScript code, you may need to modify Internet Explorer's options. Also, if you work
under a user account (not an administrator account), you may need permissions for the Machine
Debug Manager's system component. For more information, see Debugging Scripts in
TestComplete in TestComplete help.
• Variables that are declared with the Dim statement within a routine are only visible within that
routine. Variables that are used without declaring them with Dim, become global variables. This
behavior may cause hidden influence of routines onto other routines. For instance, the execution of
the following code never ends:
[VBScript]
Sub ChildSub
For i = 0 To 5
...
Next
End Sub

Sub ParentSub
For i = 0 To 10
ChildSub
Next
End Sub

This happens because after a call to ChildSub, the i variable is always 5 and never 10, so the
loop within the ParentSub procedure becomes an infinite loop.

• The OnStopTest event is not generated if the script written in VBScript stops upon an unhandled
exception.
• If you have VBScript engine ver. 5 or later, you can create and use classes in your scripts. For
more information on VBScript classes, see Microsoft Development Network
(http://msdn.microsoft.com/en-us/library/ms950396.aspx).
Note that you can create class instances only in the unit, in which the class is defined. Creating a
class from another unit will cause an error. The following code demonstrates this:
[VBScript]

[UnitA]
Class MyClass
...
End Class

Sub TestRotuine
...
' Creating class in the same unit
Set cls = New MyClass ' OK!

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


100 Scripting

...
End Sub

[UnitB]

'USEUNIT UnitA

Sub AnotherRoutine
...
' Creating class in another unit
Set cls = New MyClass ' Error!
...
End Sub
To solve the problem, you can create a helper routine in the unit, in which the class is defined. This
routine will create a class instance and return it. You can then call this routine from another unit
and work with the created class instance in a usual manner:
[VBScript]

[UnitA]

Class MyClass
...
End Class

' This routine creates and returns a new class instance


Function GetClassInstance
Set GetClassInstance = New MyClass
End Function

[UnitB]

'USEUNIT UnitA

Sub AnotherRoutine
...
' Calling a routine defined in UnitA.
' Do not forget to include this unit with the USEUNIT statement
Set cls = GetClassInstance ' OK !
...
End Sub

DelphiScript
DelphiScript support is built into TestComplete. The usage of DelphiScript has the following peculiarities:
• The size of a DelphiScript unit in TestComplete cannot exceed 1 MB. This limitation does not
exist for projects created in other scripting languages (VBScript, JScript, C++Script and
C#Script).
• In TestComplete script units can refer to each other, so you can call routines and variables defined
in one unit from another unit. DelphiScript supports circular references between units.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Supported Scripting Languages – Peculiarities of Usage 101

• In Object Pascal, the body of a function or a procedure can contain declarations of other functions
and procedures, for example:
[Delphi]
procedure FuncA;

procedure FuncB;
begin

end;

begin

end;

Nested routine declarations are not allowed in DelphiScript scripts that are run from
TestComplete. This restriction does not exist in Delphi Connected Applications.
• DelphiScript’s ExceptionMessage function cannot be evaluated in TestComplete’s Watch List
panel and Evaluate dialog.
• The DelphiScript engine does not allow you to call script routines located in the web pages if you
use the DOM model. This restriction does not apply to the Tag, Tree or Hybrild models. See
Calling Scripts Located on a Web Page From TestComplete Scripts.
• DelphiScript does not support the Set Next Statement command of the script debugger (see
Setting Next Statement for Execution in TestComplete help).

JScript, C++Script and C#Script


C++Script and C#Script are based on JScript, so all of these languages have the same peculiarities of usage:
• JScript, C++Script and C#Script do not support functions that obtain parameters by reference.
• In TestComplete script units can refer to each other, so you can call routines and variables defined
in one unit from another unit. JScript, C++Script and C#Script do not support circular references
between units.
• JScript, C++Script and C#Script may handle exceptions incorrectly when the try{} block
contains calls to routines defined in other units. That is, the try... catch... finally block
works correctly only when it does not contain calls to routines from other units.
• To debug JScript, C++Script and C#Script code, you may need to modify Internet Explorer's
options. Also, if you work under a user account (not an administrator account), you may need
permissions for the Machine Debug Manager's system component. For more information, see
Debugging Scripts in TestComplete in TestComplete help.
• The format of arrays created by the JScript engine differs from arrays created in VBScript or
DelphiScript. The arrays in JScript, C++Script and C#Script are objects, while arrays created in
VBScript and DelphiScript are Variant values. This difference limits the use of some routines (for
instance, the Find and FindAll methods) in JScript, C++Script and C#Script code. In order to
use a JScript array with these routines, you need to convert the array to the format adopted in
VBScript and DelphiScript. Below is a typical conversion routine:

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


102 Scripting

[JScript]
function ConvertJScriptArray(JScriptArray)
{
// Uses the Dictionary object to convert JScript array
var objDict = Sys.OleObject("Scripting.Dictionary");
objDict.RemoveAll();
for (var i in JScriptArray)
objDict.Add(i, JScriptArray[i]);
return objDict.Items();
}

[C++Script, C#Script]
function ConvertJScriptArray(JScriptArray)
{
// Uses the Dictionary object to convert JScript array
var objDict = Sys["OleObject"]("Scripting.Dictionary");
objDict["RemoveAll"]();
for (var i in JScriptArray)
objDict["Add"](i, JScriptArray[i]);
return objDict["Items"]();
}

• Variables that are declared with the var statement within a function are only visible within this
function. Variables that are used without declaring them with var, become global variables. This
behavior may cause hidden influence of functions onto other functions. For instance, the execution
of the following code never ends:
[JScript, C++Script, C#Script]
function ChildFunc()
{
for(i = 0; i < 5; i++)

}

function ParentFunc()
{
for(i = 0; i < 10; i++)
ChildFunc();
}

This happens because after a call to ChildFunc, the i variable is always 5 and never 10, so the
loop within the ParentFunc function becomes an infinite loop.
• When a variable goes out of scope, it is released. However, if the variable held a reference to an
object, the JScript engine does not release this object until the entire script run is over. This
happens because the JScript engine cleans up memory and references at a certain point and not
when a variable is destroyed or you set it to null.
This restriction may cause problems when working with certain program objects and COM
servers. Suppose you have the following code:
[JScript, C++Script, C#Script]

www.automatedqa.com TestComplete by AutomatedQA Corporation


Supported Scripting Languages – Peculiarities of Usage 103

function Foo()
{
Obj = new ActiveXObject("MyCOMObject.MyCOMObject");

Obj = null;
}

function MainFoo()
{

Foo();
// MyCOMObject still exists

}

In this example, MyCOMObject exists after a call to Foo. Assigning null to the Obj variable marks
it as a candidate for releasing, but the object still exists in memory. To force the releasing of all such
objects and variables, call JScript’s CollectGarbage method:
[JScript, C++Script, C#Script]
function Foo()
{
Obj = new ActiveXObject("MyCOMObject.Application");

Obj = null;
CollectGarbage(); }

The described JScript peculiarity may cause a problem with creating virtual users when performing
load tests. For more information on this, see Creating Load Tests in Scripts in TestComplete help.
• Due to certain peculiarities of the JScript engine, the instanceof operator returns an incorrect
value if the checked objects are passed between script units. Suppose you have the following code:
[JScript, C++Script, C#Script]
function fooA(){
try
{
throw new Error(10,"This is an error."); // Simulates exception
}
catch(err)
{
var res = err instanceof Error;
Log.Message("fooA: err instanceof Error = " + r);
fooB(err);
}
}

function fooB(err)
{
var res = err instanceof Error;
Log.Message("fooB: err instanceof Error = " + res);
}

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


104 Scripting

If both fooA and fooB reside in the same script unit, in both functions the res variable will be
true. If you place fooB to another unit, then the res variable in fooA will be true, and the res
variable in fooB will be false.

• The OnStopTest event is not generated if the script written in JScript, C++Script or C#Script
stops upon an unhandled exception.

www.automatedqa.com TestComplete by AutomatedQA Corporation


Index 105

Index
Errors ..................................................................72
A Searching for the reason of errors ...................72
Additional information about TestComplete ........9
Analyzing .....................................................45, 70 F
Recorded script................................................45 FAQ ......................................................................9
Test results.......................................................70 Frequently asked questions...................................9
Application controls and objects ........................88
Addressing in scripts .......................................88 G
AQCommunity .....................................................9 Getting started with TestComplete .....................11
Arrays .................................................................98 Getting Support.....................................................9
in JScript, C++Script and C#Script .................98
H
C
How to ................................................................96
C#Script........................................................76, 98 Calling routines declared in another unit.........96
Peculiarities of usage.......................................98 Calling variables and constants declared in
Selecting the scripting language......................76 another unit ..................................................96
C++Script .....................................................76, 98
Peculiarities of usage.......................................98 J
Selecting the scripting language......................76
JScript ...........................................................76, 98
Calling ................................................................96
Peculiarities of usage.......................................98
Project items in scripts ....................................77
Selecting the scripting language......................76
Routines declared in another unit....................96
Variables and constants declared in another unit
L
......................................................................96
Checkpoints ........................................................18 Languages.....................................................76, 98
About...............................................................18 Comparing features of scripting languages .....76
Creating at design time....................................60 Peculiarities of usage.......................................98
Creating during recording ...............................42 Selecting the scripting language......................76
Community site ....................................................9
Controls N
Addressing in scripts .......................................88 Naming processes and windows.........................88
Recognizing windows and controls.................88 Newsgroups about TestComplete .........................9
Creating a project ...............................................21
O
D Overview ..............................................................4
DelphiScript..................................................76, 98
Peculiarities of usage.......................................98 P
Selecting the scripting language......................76 Processes
Difference between various TestComplete editions Recognition of .................................................88
...........................................................................4 Project items .......................................................13
Projects
E Creating ...........................................................21
Enterprise edition of TestComplete ......................4

© 1999-2009 AutomatedQA Corp. www.automatedqa.com/support


106 Index

R Test items............................................................63
Recognizing Specifying the execution flow .........................63
Processes, windows and controls ....................88 Test results..........................................................70
Recording Scripts ...............................................38 Analyzing ........................................................70
Resources..............................................................9 TestComplete
Results ................................................................70 Community site .................................................9
Analyzing ........................................................70 Difference between Standard and Enterprise
Running the created test .....................................67 editions ...........................................................4
FAQ...................................................................9
S Getting started .................................................11
Newsgroups .......................................................9
Scripting .............................................................74 Overview .....................................................4, 11
Comparing features of scripting languages .....76 Projects and project items................................13
Overview .........................................................74 Supported development tools ............................8
Quick start .......................................................77 System requirements .........................................6
Scripting languages .........................................76 Technical support ..............................................9
Supported languages – Peculiarities of usage .98 Tested applications .............................................25
Scripting languages ......................................76, 98 Defining applications to test............................25
Comparing features of scripting languages .....76 Tests....................................................................36
Peculiarities of usage.......................................98 About...............................................................36
Selecting the scripting language......................76 Creating ...........................................................36
Scripts .................................................................38 Running the created test ..................................67
About writing scripts.......................................74 Specifying the execution flow .........................63
Analyzing recorded script ...............................45
Quick start .......................................................77 U
Recognition of processes and windows...........88
Recording ........................................................38 uses statement – About .......................................96
Writing scripts .................................................74
Writing scripts – Quick start ...........................77 V
Specifying the execution flow for tests and test VBScript .......................................................76, 98
items ................................................................63 Peculiarities of usage.......................................98
Standard edition of TestComplete ........................4 Selecting the scripting language......................76
Support .................................................................9
Supported development tools ...............................8 W
System requirements.............................................6 Windows
Recognition of .................................................88
T
Technical support .................................................9

www.automatedqa.com TestComplete by AutomatedQA Corporation

S-ar putea să vă placă și