Effective GUI Test Automation Developing an Automated GUI Testing Tool phần 3 pps

46 214 0
Effective GUI Test Automation Developing an Automated GUI Testing Tool phần 3 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

75 C# API Text Viewer Now you have prepared all the pieces for the C# API Text Viewer. The last thing to do is dis- play the converted C# definitions stored in the definition lists. To do this, you will program the Windows form and make a user-friendly GUI. GUI of the C# API Text Viewer When you started the CSharpTextViewer project, the Microsoft Visual Studio .NET IDE cre- ated a Windows form with a default name, Form1. The code for this form is saved as Form1.cs. Open the Solution Explorer, rename the file CSharpTextViewer.cs, and keep the rest intact. Then add the GUI components onto the form as they are described in the following list (just change the values of the listed properties and accept the default values of the other properties): Control Property Value MainMenu Name mnuMainAPI OpenFileDialog Name opnFileDialog Label Text API Type: Label Text Type the first few letters of the function name you look for: Label Text Available functions: Label Text Selected functions: ComboBox Name cmbAPITypes TextBox Name txtLookfor Text Look for functions ListBox Name lstAvailableFuncs RichTextBox Name txtSelected Text Selected functions Button Name btnAdd Text Add Button Name btnRemove Text Remove Button Name btnClear Text Clear Button Name btnCopy Text Copy 4351c03.fm Page 75 Tuesday, September 28, 2004 12:20 PM 76 Chapter 3 • C# Win32 API Programming and Test Monkeys Follow these steps to make a File menu and a Help menu. 1. Select the mnuMainAPI GUI object at the bottom below the form. The menu object on the top of the form displays a gray string Type Here. 2. Type File to replace the words Type Here. The word File appears on the main menu. Select the File menu and its (Name) property. Set its name to mnuFile. 3. Type Help as in step 2 to make its (Name) property mnuHelp. 4. Select the File menu. Replace the words Type Here with Open to create a submenu under the File menu. Set its (Name) property to mnuFileOpen. 5. Type a hyphen (-) below the Open menu. Set its name to mnuFileSep. 6. Type Exit below mnuFileSep. Set its name to mnuFileExit. 7. You can repeat step 4 to create a submenu under the Help menu. However, I leave the coding task for the Help clicking event in your hands. Figure 3.4 shows the populated menu items. After you finish populating the GUI controls, the Windows form looks like the form in Figure 3.5. Now, the front end GUI objects are completely done. You need to add code for the buttons and the menu items. Based on the requirements of the API Text Viewer, these menu items and the buttons should perform the following actions when they are clicked: Exit menu Terminate the application. Open menu Initialize the ConstantViewer, DllImportViewer, and StructViewer classes with Win32API.txt. FIGURE 3.4 The appearance of the main menu for the C# API Text Viewer project Control Property Value GroupBox Name grpScope RadioButton Name rdPublic Text public RadioButton Name rdPrivate Text private 4351c03.fm Page 76 Tuesday, September 28, 2004 12:20 PM 77 C# API Text Viewer FIGURE 3.5 The GUI front end of the C# API Text Viewer project Help menu Provide users with instructive help. However, this chapter will not include code for this menu. You can add instructional help hints for users later. For reference, the sample source code on www.sybex.com has an example of a Help menu code. cmbAPITypes ComoBox Populate items of Constants, Types and Declares. When an item is selected, the corresponding keys of the definition list are loaded into the lstAvailableFuncs object. txtLookFor TextBox As the user types in the first few letters, the C# API Text Viewer will select a Win32 custom function which starts with the letters in the lstAvailableFuncs object. btnAdd Button Append the C# definition from a definition list according to the selected item in the lstAvailableFuncs object. btnRemove Button Remove a line of text located where the cursor is in the txtSelected (RichTextBox) object. btnClear Button Clear the text in the txtSelected text box. btnCopy Button Set the text in the txtSelected text box to the clipboard. Later, the user can paste the clipboard contents into the code editor in the Microsoft Visual Studio .NET IDE. To start the implementation for the Exit menu, double-click the Exit menu item from the form editor. The Microsoft Visual Studio .NET IDE brings your cursor to the code editor. 4351c03.fm Page 77 Tuesday, September 28, 2004 12:20 PM 78 Chapter 3 • C# Win32 API Programming and Test Monkeys Between the curly brackets of the automated generated code skeleton, type in code like this: private void mnuFileExit_Click(object sender, System.EventArgs e) { Application.Exit(); } Addition of the Application.Exit() is self-explanatory. When the Exit menu is clicked, Application.Exit() is invoked to terminate this session of the C# API Text Viewer. Then double-click the Open menu and code this mnuFileOpen_Click() event as follows: private void mnuFileOpen_Click(object sender, System.EventArgs e) { string filename = ""; if (opnFileDialog.ShowDialog() == DialogResult.OK) { filename = opnFileDialog.FileName; OpenAPITextFile(filename); } else return; } The mnuFileOpen_Click() event first simply opens a File Open dialog box. After the user selects a text file, it executes an OpenAPITextFile() helper method as the following code shows: private ConstantViewer constViewer; private StructViewer structViewer; private DllImportViewer dllImportViewer; private void OpenAPITextFile(string filename) { FillAPITypeCombobox(); constViewer = new ConstantViewer(filename); Thread tConst = new Thread(new ThreadStart(constViewer.ParseText)); tConst.Start(); structViewer = new StructViewer(filename); Thread tStruct = new Thread(new ThreadStart(structViewer.ParseText)); tStruct.Start(); dllImportViewer = new DllImportViewer(filename); Thread tDllImport = new Thread(new ThreadStart(dllImportViewer.ParseText)); tDllImport.Start(); System.Threading.Thread.Sleep(1000); this.cmbAPITypes.Text = this.cmbAPITypes.Items[1].ToString(); } 4351c03.fm Page 78 Tuesday, September 28, 2004 12:20 PM 79 C# API Text Viewer The declarations of the three private fields, constViewer, structViewer, and dllImportViewer, enable other helper methods within the class to have access to them after they are initialized inside the OpenAPITextFile() method. Within the method declaration, the first line invokes another helper method to populate the definition categories into the ComboBox object, cmbAPITypes. The code for the FillAPITypeCombobox() helper method is as follows: private void FillAPITypeCombobox() { cmbAPITypes.Items.Clear(); cmbAPITypes.Items.Add("Constants"); cmbAPITypes.Items.Add("Declares"); cmbAPITypes.Items.Add("Types"); } This FillAPITypeCombobox() helper method calls the Add() method of the ComboBox control and the possible values. The rest of the code in the OpenAPITextFile() method simply initializes objects of the ConstantViewer, DllImportViewer, and StructViewer classes, respectively, and start threads to invoke the ParseText() methods in sequence. When all the objects are initialized, it uses the Sleep() method from the Thread class to let the program pause for a second. This will allow time for the execution to respond to the cmbAPITypes_SelectedIndexChanged() event. After coding the OpenAPITextFile() method, you double-click the ComboBox object, cmbAPITypes. Add code to the cmbAPITypes_SelectedIndexChanged() event: private void cmbAPITypes_SelectedIndexChanged(object sender, System.EventArgs e) { Thread tConst; switch (cmbAPITypes.Text) { case "Constants": tConst = new Thread(new ThreadStart(UpdateConstants)); tConst.Start(); break; case "Declares": tConst = new Thread(new ThreadStart(UpdateDllImports)); tConst.Start(); break; case "Types": tConst = new Thread(new ThreadStart(UpdateStructs)); tConst.Start(); break; } } 4351c03.fm Page 79 Tuesday, September 28, 2004 12:20 PM 80 Chapter 3 • C# Win32 API Programming and Test Monkeys In each case, when the selected index in the ComboBox object is changed, the change of selected index starts a thread to invoke one of the three helper methods. The UpdateConstants() method is coded as follows: private void UpdateConstants() { int i; Monitor.Enter(this); this.lstAvailableFuncs.Items.Clear(); for (i = 0; i < constViewer.Count; i++) { this.lstAvailableFuncs.Items.Add(constViewer.GetKey(i)); } Monitor.Exit(this); } The UpdateConstants() method calls a pair of static methods, Monitor.Enter() and Monitor.Exit(), from the Threading namespace. The Monitor class controls access to objects by granting a lock for an object to a single thread. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use Monitor to ensure that no other thread is allowed to access a section of application code being executed by the lock owner unless the other thread is executing the code using a different locked object. Within the monitor method calls, a for loop adds all the constant names to the list box by invoking the GetKey() method. The code for the UpdateDllImports() and UpdateStructs() methods are very similar to the code for the UpdateConstants() method. The only difference is that each uses an object of a particular class to update the list box: private void UpdateDllImports() { int i; Monitor.Enter(this); this.lstAvailableFuncs.Items.Clear(); for (i = 0; i < dllImportViewer.Count; i++) { lstAvailableFuncs.Items.Add(dllImportViewer.GetKey(i)); } Monitor.Exit(this); } private void UpdateStructs() { int i; Monitor.Enter(this); lstAvailableFuncs.Items.Clear(); 4351c03.fm Page 80 Tuesday, September 28, 2004 12:20 PM 81 C# API Text Viewer for (i = 0; i < structViewer.Count; i++) { lstAvailableFuncs.Items.Add(structViewer.GetKey(i)); } Monitor.Exit(this); } Thus, when the text is changed in the combo box, the content in the list box is changed accordingly. Double-click the TextBox object, txtLookFor. Add code to change the selected index in the list box when the txtLookfor_TextChanged() event is triggered: private void txtLookfor_TextChanged(object sender, System.EventArgs e) { lstAvailableFuncs.SelectedIndex = ➥lstAvailableFuncs.FindString(txtLookfor.Text); } This is also a simple event to code. The list box uses its FindString() method to match the first part of an item with the text in the text box. When an item matches, that item is selected. Next you are going to code the remaining buttons. To code the Add button, double-click the Add button in the design editor and insert code for the btnAdd_Click() event in the code editor: private void btnAdd_Click(object sender, System.EventArgs e) { string cSharpCode = ""; switch (this.cmbAPITypes.Text) { case "Types": cSharpCode = structViewer.GetCSharpSyntax( ➥lstAvailableFuncs.SelectedIndex); break; case "Declares": cSharpCode = dllImportViewer.GetCSharpSyntax( ➥lstAvailableFuncs.SelectedIndex); break; case "Constants": cSharpCode = constViewer.GetCSharpSyntax( ➥lstAvailableFuncs.SelectedIndex); break; } if (rdPrivate.Checked) { cSharpCode = cSharpCode.Replace( ➥APIUtility.CSHP_SCOPE, rdPrivate.Text.ToLower()); } else { 4351c03.fm Page 81 Tuesday, September 28, 2004 12:20 PM 82 Chapter 3 • C# Win32 API Programming and Test Monkeys cSharpCode = cSharpCode.Replace( ➥APIUtility.CSHP_SCOPE, rdPublic.Text.ToLower()); } if (txtSelected.Text.IndexOf(cSharpCode) < 0) txtSelected.Text += cSharpCode + "\n"; } The btnAdd_Click() event uses a switch statement to extract C# definitions from the definitionList of the viewer classes based on the selected item in the list box. Then it looks for the radio button that is checked. A checked private radio button makes a private declara- tion. Otherwise, a public declaration is made. Finally, the retrieved C# definition is added to the rich text box if this definition is not added already. At this point, the main actions are completed. The following implementation is to make this Text Viewer mimic the old API Text Viewer in the Microsoft Visual Studio 6 package. Because the rich text box is similar to a mini text editor, you can manually perform the tasks that clicking the Clear, Remove, and Copy buttons would perform. However, as the rest of this section continues, you will finish coding these events to provide so these tasks can be per- formed with the click of a button. Double click the Remove button. Add code to remove text from the rich text box. private void btnRemove_Click(object sender, System.EventArgs e) { string selectFuncs = txtSelected.Text; int currCursorPos = txtSelected.SelectionStart; int funcStartAt = currCursorPos - 1; int funcEndAt = currCursorPos + 1; GetFunctionStartPosition(selectFuncs, ref funcStartAt, true); GetFunctionStartPosition(selectFuncs, ref funcEndAt, false); string postRmStr = ""; if (funcStartAt > 0) postRmStr = selectFuncs.Substring(0, funcStartAt); postRmStr += selectFuncs.Substring(funcEndAt); txtSelected.Text = postRmStr; } The btnRemove_Click() event calls a GetFunctionStartPosition() helper method to find the starting and ending points for the text line to be removed. The GetFunctionStartPosition() method is coded as follows: private int GetFunctionStartPosition( ➥string txt, ref int currCP, bool lookForStart) { 4351c03.fm Page 82 Tuesday, September 28, 2004 12:20 PM 83 C# API Text Viewer if (currCP < 0) return 0; if (currCP > txt.Length - 1) { currCP = txt.Length; return 0; } char[] chr = txt.ToCharArray(); while (chr[currCP] != '\n') { if (lookForStart) { if (currCP > 0) currCP -=1; else break; } else { if (currCP < txt.Length-1) currCP += 1; else break; } } return 0; } Double-click the Clear button. Add code to have the btnClear_Click() event implemented: private void btnClear_Click(object sender, System.EventArgs e) { txtSelected.Text = ""; } The btnClear_Click() event simply resets the rich text box to empty. And finally, double- click the Copy button. The btnCopy_Click() event also executes only one line of code: private void btnCopy_Click(object sender, System.EventArgs e) { Clipboard.SetDataObject(txtSelected.Text, true); } After the btnCopy_Click() event, the C# code in the rich text box is copied to the clipboard and is ready to be pasted into a C# program. For users’ convenience in the future, you can load WIN32API.TXT automatically when you start the C# API Text Viewer. In order to do this, you double-click on an empty spot of the form 4351c03.fm Page 83 Tuesday, September 28, 2004 12:20 PM 84 Chapter 3 • C# Win32 API Programming and Test Monkeys and the Microsoft Visual Studio .NET IDE generates a Form1_Load() event. Add code between the curly brackets and the completed code look like the following: private void Form1_Load(object sender, System.EventArgs e) { txtLookfor.Clear(); txtSelected.Clear(); try { OpenAPITextFile(@"C:\Program Files\ ➥Microsoft Visual Studio\Common\Tools\Winapi\WIN32API.TXT"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } When the form is loaded, the text boxes are cleared and the method OpenAPITextFile() is invoked to open Win32API.txt automatically. The path and filename of Win32API.txt are hard- coded within a try-catch statement. There are two reasons to hard-code this line of code: ● To open an existing copy of the Win32API.txt automatically each time when the C# API Text Viewer starts. Thus users can engage in C# API programming immediately. However, if the user’s system doesn’t have the hard coded path and filename, the C# API Text Viewer will still start without problem. But the user has to open the Win32API.txt manually. ● To allow the GUI testing tool developed in the upcoming chapters to test the GUI compo- nents of the C# API Text Viewer before the automatic menu handling capability is added. Thus, it is recommended that your hard coded path and filename is consistent with you computer system If you don’t have the old version of WIN32API.TXT on your system, you can copy the new version of the file with the same name from the sample code for this book to your preferred directory. You can alter the path name based on the physical location of the WIN32API.TXT file. The @-quoted string is called a verbatim string to avoid specifying escape characters. That is all the code for the C# API Text Viewer. Build and run the project by pressing F5. You will enjoy C# API programming with the assistance of this tool. It will help make your future projects progress more quickly. NOTE The source code for this tool is included in the Chapter03/CSharpAPITextViewer folder with the other examples. You can download the updated code from www.sybex.com if you haven’t done so yet. 4351c03.fm Page 84 Tuesday, September 28, 2004 12:20 PM [...]... manual process; you can not use it directly in the automatic testing tool But it gives you an idea about what information is needed to test GUIs Many commercial GUI testing tools have utilities similar to Spy++ for users to manually relocate and probe GUI components The next sections will explore in more depth how to use the user32.dll to find GUI information automatically Functions from the User32.dll... develop a GUI testing tool to invoke these functions, thus a GUI test library will ensure that the tool can share these functions to help with writing a test script automatically and performing the testing tasks in the test scripts for various testing projects There are hundreds of functions in the user32.dll We will use only some of these functions in the tool projects For example, Chapter 3 used a... user32.dll Therefore, the user32.dll will be the DLL most frequently referred to for Win32 API programming This chapter will briefly introduce you to it and guide you in developing a GUI test library Occasionally, functions of other Win32 subsystems will also be needed, such as kernel32.dll and gdi32.dll When this happens, I will explain these functions specifically GUI Test and the Custom User32.dll... Viewer, you developed a test monkey to move the mouse and click the buttons You then gave the test monkey more capabilities In the upcoming chapters, you are going to build an intelligent tool to test GUI applications Chapter 4 Developing a GUI Test Library 100 Chapter 4 • Developing a GUI Test Library he purpose of developing a test script is to programmatically simulate a person using an application by... Testing The goal of this book is to build a GUI testing tool with full automation to generate test cases, test scripts, and bug reports By using a few of the custom functions, you have developed a very primitive test monkey, but it is far from being a fully automated test tool To achieve the proposed goal, the first and most critical step is to build a reusable GUI testing library This library will be able... the scene Automated software test tools provide test script languages and ask testers to write or record test scripts The goal of the test scripts is to simulate a person performing the mouse and key actions on a selected GUI component and to verify the outcome T This book shows you how to develop a tool with the capability of writing test scripts in programming languages Often, a programming language... the GUI components It will be able to write a test script for each specific component found The library will be used both for the tool and for the test script to perform the desired human actions It will also provide a harness to manage the automatically generated test scripts However, we will use the NET Framework to develop the testing tool and to enable the tool to write test scripts in C# language... marshal the unmanaged code To marshal the custom Win32 DLLs, we mainly use a few methods of the Marshal class and the DllImport attribute There are numerous constants, types, and functions predefined by the Win32 API programming method Many of them need to be used to develop a GUI testing tool You won’t make use all of the functions, but you can use more of them to update your testing tool after you... information automatically Functions from the User32.dll for GUI Testing Now, you have enough background to develop a GUI testing library This library will become the core of a GUI testing tool You can open the Microsoft Visual Studio NET IDE to start a new Class Library project, type in GUITestLibrary as the project name, and place it in a new C:\GUISourceCode\Chapter04 folder When the project shows on... of GUITestLibrary and a default class name, Class1 You can rename Class1 to GUITestActions to make it easier to identify The code generated by the Microsoft Visual Studio NET IDE looks like Listing 4.1 108 Chapter 4 • Developing a GUI Test Library ➲ Listing 4.1 Auto-Generated Code for the GUITestActions Class using System; namespace GUITestLibrary { /// /// Summary description for GUITestActions . this, you double-click on an empty spot of the form 435 1c 03. fm Page 83 Tuesday, September 28, 2004 12:20 PM 84 Chapter 3 • C# Win32 API Programming and Test Monkeys and the Microsoft Visual. MOUSE_MICKEYS = 65 535 ; 435 1c 03. fm Page 85 Tuesday, September 28, 2004 12:20 PM 86 Chapter 3 • C# Win32 API Programming and Test Monkeys When the C# API Text Viewer is running with the Win32API.txt file. Thread(new ThreadStart(UpdateStructs)); tConst.Start(); break; } } 435 1c 03. fm Page 79 Tuesday, September 28, 2004 12:20 PM 80 Chapter 3 • C# Win32 API Programming and Test Monkeys In each case,

Ngày đăng: 12/08/2014, 21:20

Từ khóa liên quan

Mục lục

  • Chapter 4: Developing a GUI Test Library

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan