Walkthrough: Creating, Editing and Maintaining a Coded UI Test

In this walkthrough, you will create a simple Windows Presentation Foundation (WPF) application to demonstrate how to create, edit, and maintain a coded UI test. The walkthrough provides solutions for correcting tests that have been broken by various timing issues and control refactoring.

Prerequisites

For this walkthrough you will need:

  • Visual Studio 2010 Ultimate or Visual Studio 2010 Premium.

Create a Simple WPF Application

  1. On the File menu, point to New, and then select Project.

    The New Project dialog box appears.

  2. In the Installed Templates pane, expand Visual C#, and then select Windows.

  3. Above the middle pane, verify that the target framework drop-down list is set to .NET Framework 4.

  4. In the middle pane, select the WPF Application template.

  5. In the Name text box, type SimpleWPFApp.

  6. Choose a folder where you will save the project. In the Location text box, type the name of the folder.

  7. Click OK.

    The WPF Designer for Visual Studio opens and displays MainWindow of the project.

  8. If the toolbox is not currently open, open it. Click the View menu, and then click Toolbox.

  9. Under the All WPF Controls section, drag a Button, CheckBox and ProgressBar control onto the MainWindow in the design surface.

  10. Select the Button control. In the Properties window, change the value for the Content property from Button to Start.

  11. Select the ProgressBar control. In the Properties window, change the value for Maximum property from 100 to 1000.

  12. Select the Checkbox control. In the Properties window, clear the IsEnabled property.

    Simple WPF Application

  13. Double-click the button control to add a Click event.

    The MainWindow.xmal.cs is displayed in the Code Editor with the cursor in the new button1_Click event.

  14. At the top of the MainWindow class, add a delegate. The delegate will be used for the progress bar. To add the delegate, add the following code:

            private delegate void ProgressBarDelegate(
            System.Windows.DependencyProperty dp, Object value);
    
  15. In the button1_Click method, add the following code:

                double progress = 0;
    
                ProgressBarDelegate updatePbDelegate =
            new ProgressBarDelegate(progressBar1.SetValue);
    
                do
                {
                    progress ++;
    
                    Dispatcher.Invoke(updatePbDelegate,
                        System.Windows.Threading.DispatcherPriority.Background,
                        new object[] { ProgressBar.ValueProperty, progress });
                    progressBar1.Value = progress;
                }
                while (progressBar1.Value != progressBar1.Maximum);
    
                checkBox1.IsEnabled = true;
    

Verify the WPF Application Runs Correctly

  1. On the Debug menu, select Start Debugging or press F5.

  2. Click Start.

    In a few seconds, the progress bar should be 100% complete. The check box control is now enabled.

  3. Close SimpleWPFApp.

Create and Run a Coded UI Test for SimpleWPFApp

  1. In Solution Explorer, right-click the solution, click Add and then select New Project.

    The Add New Project dialog box appears.

  2. In the Installed Templates pane, expand Visual C#, and then select Test.

  3. In the middle pane, select the Test Project template.

  4. Click OK.

    In Solution Explorer, the new test project named TestProject1 is added to your solution and the UnitTest1.cs file appears in the Code Editor. You can close the UnitTest1.cs file because it is not used in this walkthrough.

  5. In Solution Explorer, right-click TestProject1, click Add and then select Coded UI test.

    The Generate Code for Coded UI Test dialog box appears.

  6. Select the Record actions, edit UI map or add assertions option and click OK.

    The UIMap – Coded UI Test Builder appears.

    For more information about the options in the dialog box, see How to: Create a Coded UI Test.

  7. Locate and run the SimpleWPFApp application that you created earlier. By default, the application will be located at C:\Users\<username>\Documents\Visual Studio 2010\Projects\SimpleWPFApp\SimpleWPFApp\bin\Debug\SimpleWPFApp.exe

  8. Create a desktop shortcut to the SimpleWPFApp application. Right-click SimpleWPFApp.exe and choose Copy. On your desktop, right-click and choose Paste shortcut.

    Tip

    A shortcut to the application makes it easier to add or modify Coded UI tests for your application because it lets you start the application quickly. You do not have to navigate to it. You will have to run the application again in this walkthrough.

  9. Click Start Recording on the UIMap – Coded UI Test Builder. In a few seconds, the Coded UI Test Builder will be ready.

  10. Run SimpleWPFApp.exe using the desktop shortcut.

  11. On the SimpleWPFApp, click Start.

    In a few seconds, the progress bar should be 100 complete. The check box control is now enabled.

  12. Select the box for the CheckBox control.

  13. Close the SimpleWPFApp application.

  14. On the UIMap - Coded UI Test Builder, click Generate Code.

  15. In the Method Name type SimpleAppTest and click Add and Generate. In a few seconds, the Coded UI test appears and is added to the Solution.

  16. Close the UIMap – Coded UI Test Builder.

    The CodedUITest1.cs file appears in the Code Editor.

Run the Coded UI Test

  • In the CodedUITest1.cs file, locate the CodedUITestMethod method, right-click and select Run Tests.

    While the coded UI test runs, the SimpleWPFApp is visible. It conducts the steps that you did in the previous procedure. However, when the test tries to select the check box for the CheckBox control, the Test Results window shows that the test failed. This is because the test tries to select the check box but is not aware that the CheckBox control is disabled until the progress bar is 100% complete. You can correct this and similar issues by using the various UITestControl.WaitForControlXXX() methods that are available for coded UI testing. The next procedure will demonstrate using the WaitForControlEnabled() method to correct the issue that caused this test to fail. For more information, see Making Coded UI Tests Wait For Specific Events During Playback.

Edit and Rerun the Coded UI Test

  1. In the Test Results window, right-click the failed test and select View Test Results Details.

    The CodedUITestMethod1[Results] is displayed.

  2. In the Error Stack Trace section, click the first link next to TestProject1.UIMap.SimpleAppTest().

    The UIMap.Designer.cs file opens with the point of error highlighted in the code:

    // Select 'CheckBox' check box
    uICheckBoxCheckBox.Checked = this.SimpleAppTestParams.UICheckBoxCheckBoxChecked;
    
  3. To correct this problem, you can make the coded UI test wait for the CheckBox control to be enabled before continuing on to this line using the WaitForControlEnabled() method.

    Warning

    Do not modify the UIMap.Designer.cs file. Any code changes you make in the UIMapDesigner.cs file will be overwritten every time you generate code using the UIMap - Coded UI Test Builder. If you have to modify a recorded method, you must copy it to UIMap.cs file and rename it. The UIMap.cs file can be used to override methods and properties in the UIMapDesigner.cs file. You must remove the reference to the original method in the Coded UITest.cs file and replace it with the renamed method name.

  4. In the UIMapDesinger.cs file, select all the code for the entire SimpleAppTest method and copy it.

  5. In Solution Explorer, open the UIMap.cs file.

  6. Paste the SimpleAppTest method code into the UIMap partial class.

  7. Rename the method from SimpleAppTest() to ModifiedSimpleAppTest()

  8. Add the following using statement to the file:

    using Microsoft.VisualStudio.TestTools.UITesting.WpfControls;
    
  9. Add the following WaitForControlEnabled() method before the offending line of code identified previously:

    uICheckBoxCheckBox.WaitForControlEnabled();
    
    // Select 'CheckBox' check box
    uICheckBoxCheckBox.Checked = this.SimpleAppTestParams.UICheckBoxCheckBoxChecked;
    
  10. In the CodedUITest1.cs file, locate the CodedUITestMethod method and either comment out or rename the reference to the original SimpleAppTest() method and then replace it with the new ModifiedSimpleAppTest():

    [TestMethod]
            public void CodedUITestMethod1()
            {
                // To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
                // For more information on generated code, see https://go.microsoft.com/fwlink/?LinkId=179463
                //this.UIMap.SimpleAppTest();
                this.UIMap.ModifiedSimpleAppTest();
            }
    
  11. On the Build menu, click Build Solution.

  12. Right-click the CodedUITestMethod method and select Run Tests.

  13. This time the coded UI test successfully completes all the steps in the test and Passed is displayed in the Test Results window.

Refactor a Control in the SimpleWPFApp

  1. In the MainWindow.xaml file, in the Designer, select the button control.

  2. At the top of the Properties window, select the value button1 next to Button and change the value to buttonA.

  3. On the Build menu, click Build Solution.

  4. On the Test menu, select Windows and then click Test View.

  5. In Test View, select CodedUITestMethod1 under the Test Name column and then click Run Selection in the toolbar.

    The test fails because the coded UI test cannot locate the button control that was originally mapped in the UIMap as button1. Refactoring can impact coded UI tests in this manner.

  6. In the Test Results window, right-click the failed test and select View Test Results Details.

    The CodedUITestMethod1[Results] appears.

  7. In the Error Stack Trace section, click the first link next to TestProject1.UIMpa.SimpleAppTest().

    The UIMap.Designer.cs file opens. The point of error is highlighted in the code:

    // Click 'Start' button
    Mouse.Click(uIStartButton, new Point(27, 10));
    

    Notice that the line of code earlier in this procedure is using UiStartButton, which is the UIMap name before it was refactored.

    To correct the issue, you can add the refactored control to the UIMap by using the Coded UI Test Builder. You can update the test’s code to use the code, as demonstrated in the next procedure.

Map Refactored Control and Edit and Rerun the Coded UI Test

  1. In the CodedUITest1.cs file, in the CodedUITestMethod1() method, right-click, select Generate Code for Coded UI Test and then click Use Coded UI Test Builder.

    The UIMap – Coded UI Test Builder appears.

  2. Using the desktop shortcut you created earlier, Run the SimpleWPFApp application that you created earlier.

  3. On the UIMap – Coded UI Test Builder, drag the crosshair tool to the Start button on the SimpleWPFApp.

    The Start button is enclosed in a blue box and the Coded UI Test Builder takes a few seconds to process the data for the selected control and displays the controls properties. Notice that the AutomationUId is named buttonA.

  4. In the properties for the control, click the arrow at the upper-left corner to expand the UI Control Map. Notice that UIStartButton1 is selected.

  5. In the toolbar, click the Add control to UI Control Map.

    The status at the bottom of the window verifies the action by displaying Selected control has been added to the UI control map.

  6. On the UIMap – Coded UI Test Builder, click Generate Code.

    The Coded UI Test Builder – Generate Code appears with a note indicating that no new method is required and that code will only be generated for the changes to the UI control map.

  7. Click Generate.

  8. Close SimpleWPFApp.exe.

  9. Close UIMap – Coded UI Test Builder.

    The UIMap – Coded UI Test Builder takes a few seconds to process the UI control map changes.

  10. In Solution Explorer, open the UIMap.Designer.cs file.

  11. In the UIMap.Designer.cs file, below the constructor in the generated code class UIMainWindow, expand the Properties region. Notice that the public WpfButton UIStartButton1 property has been added.

  12. In the UIStartButton1 property, expand the Search Criteria region. Notice the SearchProperties is set to "buttonA":

    public WpfButton UIStartButton1
            {
                get
                {
                    if ((this.mUIStartButton1 == null))
                    {
                        this.mUIStartButton1 = new WpfButton(this);
                        #region Search Criteria
                        this.mUIStartButton1.SearchProperties[WpfButton.PropertyNames.AutomationId] = "buttonA";
                        this.mUIStartButton1.WindowTitles.Add("MainWindow");
                        #endregion
                    }
                    return this.mUIStartButton1;
                }
            }
    

    Now you can modify the coded UI test to use the newly mapped control. As pointed out in the previous procedure if you want to override any methods or properties in the coded UI test, you must do so in the UIMap.cs file.

  13. In the UIMap.cs file, add a constructor and specify the SearchProperties property of the UIStartButton property to use the AutomationID property with a value of "buttonA":

    public UIMap()
            {
                this.UIMainWindowWindow.UIStartButton.SearchProperties[WpfButton.PropertyNames.AutomationId] = "buttonA";
            }
    
  14. On the Build menu, click Build Solution.

  15. In Test View, select CodedUITestMethod1 under the Test Name column, In the toolbar, click Run Selection.

    This time, the coded UI test successfully completes all the steps in the test. In the Test Results Window, you will see a status of Passed.

External Resources

Videos

link to videoCoded UI Tests-DeepDive-Episode1-GettingStarted

link to videoCoded UI Tests-DeepDive-Episode2-MaintainenceAndDebugging

link to videoCoded UI Tests-DeepDive-Episode3-HandCoding

Hands on lab

MSDN Virtual LabMSDN Virtual Lab: Introduction to Creating Coded UI Tests with Visual Studio 2010

FAQ

Coded UI Tests FAQ - 1

Coded UI Tests FAQ -2

Forum

Visual Studio UI Automation Testing (includes Coded UI)

See Also

Tasks

How to: Create a Coded UI Test

Concepts

Testing the User Interface with Automated UI Tests

Supported Configurations and Platforms for Coded UI Tests and Action Recordings

Other Resources

Getting Started with the WPF Designer