Advanced Coded UI Testing

62
© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel www.sela.co.il SELA DEVELOPER PRACTICE May 5-9, 2013 Shai Raiten Advanced Coded UI Testing Using Visual Studio 2012

description

Shai Raiten's talk at the SELA Developer Practice (May 2013) about Advanced Coded UI using Visual Studio 2012. This presentation explain how to work with multiple UI maps, how to use various types of data sources, how to use LINQ and Reflection for project refactoring, and how to create and use logs and traces.

Transcript of Advanced Coded UI Testing

Page 1: Advanced Coded UI Testing

SELA DEVELOPER PRACTICEMay 5-9, 2013

Shai Raiten

Advanced Coded UI Testing Using Visual Studio 2012

Page 2: Advanced Coded UI Testing

Agenda• Coded UI Testing Overview

• Fast Forward Automation Using MTM

• Understand Coded UI Anatomy

• Getting Started with Coded UI Testing

• Web

• Desktop

• Data Collectors

• Creating Custom Data Collector

• Data Binding

• Advanced Coded UI

• Tips & Tricks

Page 3: Advanced Coded UI Testing

3

What’s Coded UI Test

Coded UI Tests are automated tests that drive your

application through its user interface. These tests

include functional testing of the UI controls. They let

you verify that the whole application, including its user

interface, is functioning correctly. Coded UI Tests are

particularly useful where there is validation or other

logic in the user interface, for example in a web page.

Page 4: Advanced Coded UI Testing

4

Coded UI Features

• Functional Testing

• Generate code in C#/VB

• Intent aware recording and resilient playback

• Integrated with ALM story

• Build, deploy & test in lab or as part of build

• Local, remote runs, data collection

• Rich Extensibility

Page 5: Advanced Coded UI Testing

Intent Aware RecordingClick Start buttonClick on the search boxType keyword in the search boxClick the correct search result

Search for the keywordClick the correct search result

Launch the application or url

Inte

nt

Page 6: Advanced Coded UI Testing

Resilient Playback

Search

• Search for the Control based on the “Query ID” generated during recording

WFR

• Wait for Control to be Ready: The playback needs to ensure that the control is ready to be acted upon

Ensure Visible

• Ensure that the control is visible (i.e. ensure point is clickable and scrolled into view)

UI Syn

c

• Playback tries to ensure that the control that was supposed to have received an action has actually received it

Page 7: Advanced Coded UI Testing

Creating Coded UI Test

• Coded UI Test can be created the following ways:

• Fast Forward Automation using MTM

• Generating your Coded UI form existing recoding (Convert

the recorded actions from a manual test)

• Generating a new Coded UI Test from scratch using Coded

UI Test Builder

• Writing your own Coded UI (Advance option)

Page 8: Advanced Coded UI Testing

Coded UI With MTM

• Microsoft Test Manager is a platform you can use to create and manager your test plans and test cases• We can execute the test case manually, record the

actions on the UI and generate them to a code – This will be our Coded UI • We can playback the generated code as an

automatic test

Page 9: Advanced Coded UI Testing

DEMO

Record & Playback Testing Using MTM

Page 10: Advanced Coded UI Testing

Creating New Coded UI Project• Open Visual Studio 2012• Choose File < New < Project • Use C# Template go to Test and choose Coded UI

Project

Page 11: Advanced Coded UI Testing

Coded UI with Visual Studio• When creating a new Coded UI Project we have the

option of using the Coded UI Test Builder

Page 12: Advanced Coded UI Testing

Coded UI Test Builder

Record/Stop/PauseEdit Recorded Steps

Add AssertionsGenerate Code

Page 13: Advanced Coded UI Testing

DEMO

Record and Playback Actions Using UI Test Builder

Page 14: Advanced Coded UI Testing

Generated Coded UI Files

CodedUITest1.cs Contains the coded UI test class, test methods and assertions.

UIMap.uitest Contains the XML model for the UIMap class, including all windows, controls, properties, methods, parameters, actions, and assertions.

UIMap.Designer.cs Contains the code representation of the XML contained in the UIMap.uitest file. Do not edit this file.

UIMap.cs Contains more of the code for the UIMap class. You can put any customizations for the UI map in this file.

Page 15: Advanced Coded UI Testing

CodedUITest Class & Test Method[CodedUITest]public class CodedUITest1{... [TestMethod] public void CodedUITestMethod1() { this.UIMap.AddTwoNumbers(); this.UIMap.VerifyResultValue(); // To generate more code for this test, select // "Generate Code" from the shortcut menu. { {

Page 16: Advanced Coded UI Testing

UIMap Methods/// <summary>/// MenuNavigation/// </summary>public void MenuNavigation()} #region Variable Declarations HtmlHyperlink GrouHyperlink = this.UIWindow.UISampleDocument.GrouHyperlink; HtmlHyperlink LisHyperlink = this.UIWindow.UISampleDocument.LisHyperlink;

#endregion

// Click 'DropDownList With Grouping' link Mouse.Click(GrouHyperlink, new Point(48, 18));

// Click 'Cascading DropDown Lists' link Mouse.Click(LisHyperlink, new Point(41, 13));{

Page 17: Advanced Coded UI Testing

UIMap Properties

public virtual OpenWebSiteParams OpenWebSiteParams} get { if ((this.mOpenWebSiteParams == null)) { this.mOpenWebSiteParams = new OpenWebSiteParams(); { return this.mOpenWebSiteParams;{ }

Page 18: Advanced Coded UI Testing

UIMap Fields

[GeneratedCode("Coded UITest Builder", "11.0.60315.1")]public class OpenWebSiteParams { #region Fields /// <summary> /// Go to web page 'http://www.outlook.com/' using new browser instance /// </summary> public string UIOutlookWindowsInterneWindowUrl = "http://www.outlook.com/";

#endregion}

Page 19: Advanced Coded UI Testing

UIMap Control Mappublic HtmlHyperlink UILisHyperlink{ get } if ((this.mUILisHyperlink == null))} this.mUILisHyperlink = new HtmlHyperlink(this); #region Search Criteria this.mUILisHyperlink.SearchProperties[HtmlHyperlink.PropertyNames.Id] = null; this.mUILisHyperlink.SearchProperties[HtmlHyperlink.PropertyNames.Name] = null; this.mUILisHyperlink.SearchProperties[HtmlHyperlink.PropertyNames.Target] = null; this.mUILisHyperlink.SearchProperties[HtmlHyperlink.PropertyNames.InnerText] = "Cascading DropDown Lists"; this.mUILisHyperlink.FilterProperties[HtmlHyperlink.PropertyNames.AbsolutePath] = "/MVC3Extensions/CascadingDropDownLists/Home"; this.mUILisHyperlink.FilterProperties[HtmlHyperlink.PropertyNames.Title] = null; this.mUILisHyperlink.FilterProperties[HtmlHyperlink.PropertyNames.Href] = "http://demos.raduenuca.ro/MVC3Extensions/CascadingDropDownLists/Home"; this.mUILisHyperlink.FilterProperties[HtmlHyperlink.PropertyNames.Class] = null; this.mUILisHyperlink.FilterProperties[HtmlHyperlink.PropertyNames.ControlDefinition] = "href=\"/MVC3Extensions/CascadingDropDownL"; this.mUILisHyperlink.FilterProperties[HtmlHyperlink.PropertyNames.TagInstance] = "3"; this.mUILisHyperlink.WindowTitles.Add("Create"); #endregion } return this.mUILisHyperlink; }}

Page 20: Advanced Coded UI Testing

Search Methods

• SearchProperties - Mandatory properties that will

be used to search the control

• FilterProperties – When there is one

SearchProperties match or less, FilterProperties

turns into actions to the stage where if finds one

match.

Page 21: Advanced Coded UI Testing

Optimize UI Object Finding This is an example of an Search Criteria

public class UIMicrosoftHomePageDevDocument : HtmlDocument{ public UIMicrosoftHomePageDevDocument(UITestControl searchLimitContainer) : base(searchLimitContainer) { #region Search Criteria this.SearchProperties[HtmlDocument.PropertyNames.Id] = null; this.SearchProperties[HtmlDocument.PropertyNames.RedirectingPage] = "False"; this.SearchProperties[HtmlDocument.PropertyNames.FrameDocument] = "False"; this.FilterProperties[HtmlDocument.PropertyNames.Title] = "Microsoft Home Page | Devices and Services"; this.FilterProperties[HtmlDocument.PropertyNames.AbsolutePath] = "/en-us/default.aspx"; this.FilterProperties[HtmlDocument.PropertyNames.PageUrl] = "http://www.microsoft.com/en-us/default.aspx"; this.WindowTitles.Add("Microsoft Home Page | Devices and Services"); #endregion

{ {

Page 22: Advanced Coded UI Testing

Initialize & Cleanup#region Additional test attributes

//Use TestInitialize to run code before running each test [TestInitialize()]public void MyTestInitialize(){ //Run Initialize Code here!{

//Use TestCleanup to run code after each test has run[TestCleanup()]public void MyTestCleanup()} //Run Cleanup Code here!{

#endregion

Page 23: Advanced Coded UI Testing

Test Settings

• XML file that provides advanced settings for test execution.

• When should use .testsettings

• Collect diagnostic data to help isolate bugs in your application for Coded

UI Tests

• Run the client, server, and other parts of your application on different

machines (Local or virtual) to verify that it behaves as expected in a

distributed environment.

• Distribute a large number of tests across additional machines on different

configuration (OS/Client Browser)

Page 24: Advanced Coded UI Testing

Creating .testsettings file• Right click on your solution in the Solution Explorer

and choose to add new item, pick the Test Settings

template and add new .testsettings file.

• The new .testsettings is now placed in your solution

items

Page 25: Advanced Coded UI Testing

Test Settings Overview

• Test Setting is compound with the following settings:• Roles• Data Collectors & Diagnostics • Deployment• Setup and Cleanup Scripts• Hosts• Test Timeouts• Unit Test• Web Test

Page 26: Advanced Coded UI Testing

DEMO

Configure Your Test Settings

• To configure the your test settings, simply double click on the .testsettings file• The Test Setting window

will be display, with the General section as default

Page 27: Advanced Coded UI Testing

Data & Diagnostics

• In this module we will demonstrate how to collect

data and diagnostics data on your local machine

• We will focus on the next data collectors

• Event Log

• IntelliTrace

• System Information

• Video Recorder

• * Custom Collectors

Page 28: Advanced Coded UI Testing

Event Log

• Enable the Event Log and click to configure it• The Configuration Dialogue will be presented:

Page 29: Advanced Coded UI Testing

IntelliTrace• Enabling this collector during the test can be

helpful for programmers attempting to reproduce a bug and decreasing the time spent on debugging the application

Page 30: Advanced Coded UI Testing

System Information

• The System Information data collectors collects data about your operating system • The input is an XML file formatted in this kind of

structure

Page 31: Advanced Coded UI Testing

Video Recorder

• Video Recorder – Records the desktop (audio and video) on demand

Page 32: Advanced Coded UI Testing

DEMO

Using Data Collectors

Page 33: Advanced Coded UI Testing

33

DEMO

Creating Custom Data Collector

Page 34: Advanced Coded UI Testing

Coded UI Test Editor

• Remove unwanted UI actions• Changes the names for test methods and controls• View and Open Properties Window for selected item• Split one action into multiple methods• Adds custom code to your test methods by moving to

UImap.cs• Add a pause prior to a UI action specified in milliseconds• Identifies the location of the control in the UI of application

under test

Page 35: Advanced Coded UI Testing

DEMO

Coded UI Test Editor

Page 36: Advanced Coded UI Testing

36

Asserts

• AreEqual• AreNotEqual• AreSame• Fail• Inconclusive• IsFalse / IsTrue• IsInstanceOfType / IsNotInstanceOfType• IsNotNull / IsNull

It’s not enough just clicking the buttons

Page 37: Advanced Coded UI Testing

What are assertions?..

• Methods that let you validate properties of your user interface elements• You typically compare the value of control

properties with an expected value• Expected value can be hard coded or come

from parameters or external files• Assertions use the Unit Test assertion

methods

Page 38: Advanced Coded UI Testing

Assert Types

• They are few types of asserts Assert.AreEqual - will compare between object property

value to the expected value, if the value is True – pass the test, otherwise fail the test.

Assert.Fail – Will fail the test with not no condition if stated for example Assert.Fail(); could be used also with external condition i.e

if (!maxTestRuns == 0) Assert.Fail(“Test failed”)

Page 39: Advanced Coded UI Testing

Assert Types

• CollectionAssert Class - Verifies that two specified collections are equal, Two collections are equal if they have the same elements in the same order and quantity. i.e. CollectionAssert.AllItemsAreNotNull(actual); - will test if all items are not null

• StringAssert Class – Compare between strings i.e. StringAssert.Contains(String Value, String Substring, String Message) – will test that the first string contains the second substring, the string must be case sensitive

Page 40: Advanced Coded UI Testing

Assert Method Code/// <summary>/// CheckResult - Use 'CheckResultExpectedValues' to pass parameters into this method./// </summary>public void CheckResult(){ #region Variable Declarations WinText uIItem0Text = this.UICalculatorWindow.UIItem0Text; #endregion

// Verify that the 'Name' property of '0' label equals 'Result' Assert.AreEqual(this.CheckResultExpectedValues.UIItem0TextName, uIItem0Text.Name);

// Verify that the 'DisplayText' property of '0' label equals '0' Assert.AreEqual(this.CheckResultExpectedValues.UIItem0TextDisplayText, uIItem0Text.DisplayText);{

Page 41: Advanced Coded UI Testing

DEMO

Create Asserts

Page 42: Advanced Coded UI Testing

Create Planned Test Lists – Order Tests

• An ordered test is a container that holds other tests

and guarantees that tests run in a specific order

• You can add/remove test from an .ordertest file and

run it the Test Explorer or via TFS Build

Page 43: Advanced Coded UI Testing

DEMO

Ordered Test & Playlist

Page 44: Advanced Coded UI Testing

Data Driven Tests

• You can run your test case multiple times using

other different sets of data

• You can use MTM Test Case items as data source, as

well as XML, CSV, XSL and SQL Express

Page 45: Advanced Coded UI Testing

Data Sources TypesData Source Type Data Source Attribute Test Case in TFS [DataSource("Microsoft.VisualStudio.TestTools.DataSource.TestCase", "

http://TFSServer:8080/tfs/DefaultCollection;ProjectName", "30", DataAccessMethod.Sequential), TestMethod]

XML [DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\data.xml", "Iterations", DataAccessMethod.Sequential), DeploymentItem("data.xml"), TestMethod]

CSV [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\data.csv", "data#csv", DataAccessMethod.Sequential), DeploymentItem("data.csv"), TestMethod]

XLS DataSource("System.Data.Odbc", "Dsn=Excel Files;Driver={Microsoft Excel Driver (*.xls)};dbq=|DataDirectory|\\Data.xls;defaultdir=.;driverid=790;maxbuffersize=2048;pagetimeout=5;readonly=true", "Sheet1$", DataAccessMethod.Sequential), TestMethod]

SQL Express [DataSource("System.Data.SqlClient", "Data Source=.\\sqlexpress;Initial Catalog=tempdb;Integrated Security=True", "Data", DataAccessMethod.Sequential), TestMethod]

Page 46: Advanced Coded UI Testing

Data Driven Tests

In Visual Studio 2012 You will have to insert the DataSource attribute directly in the code in the line above your testmethod.

[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\data.csv", "data#csv", DataAccessMethod.Sequential), DeploymentItem("data.csv"), TestMethod]public void CodedUITestMethod1()} this.UIMap.CheckResultExpectedValues.UIItem0TextName = TestContext.DataRow["ResultValue"].ToString(); this.UIMap.CheckResult();{

Page 47: Advanced Coded UI Testing

Use XML As Data Source

• Create a new XML file in Visual Studio• Compose your data in the next order• Open new root tag under <Item></ Item >• Add all the other parameters between to first root tag

till his closing:<URL>http://www.formbreeze.com/demo.htm</URL> <FirstName>John</FirstName> <LastName>Doe</LastName> <Email>[email protected]</Email> <Phone>+972 054 54545454</Phone> <HeardAboutUs>Other</HeardAboutUs>

Page 48: Advanced Coded UI Testing

48

DEMO

Data Source

Page 49: Advanced Coded UI Testing

Multiple UIMaps

• Logical partitions when testing large application, each UIMap can be related to a specific module or a page, for instance Customer module or login page• Each tester can work and be responsible on

different sector, which means he will no other tester working on the same resource, avoiding multiple check-ins• Easier to maintain, you “know the ropes”, not

dealing with on file with thousands of code lines

Page 50: Advanced Coded UI Testing

DEMO

Working with Multiple UIMaps

Page 51: Advanced Coded UI Testing

Extracting Dynamic Data

• Some parts of your test framework will include a dynamic value you will to use at runtime• When creating new data it might be rendered and

presented differently or randomly.• In the following example I’ll show you how get a

text from an alert box - http://www.w3schools.com/js/tryit.asp?filename=tryjs_alert

Page 52: Advanced Coded UI Testing

Extract property value from an object (UIMap)

The first step is creating a new browser launch within the wanted URL

public void LaunchPassGen()

{

BrowserWindow PassGenWindow;

PassGenWindow = BrowserWindow.Launch("http://www.w3schools.com/js/tryit.asp?filename=tryjs_alert");

}

Page 53: Advanced Coded UI Testing

Extract property value from an object (UIMap)

Second step is to automate the click on the button that executes the popup windowYou can either record it or hand code it

public void ClickBTN()

{

#region Variable Declarations

HtmlInputButton uIShowalertboxButton = this.UITryitEditorv17WindowWindow.UITryitEditorv17Document.UIViewFrame.UIHttpwwww3schoolscomjDocument.UIShowalertboxButton;

#endregion

// Click 'Show alert box' button

Mouse.Click(uIShowalertboxButton, new Point(53, 11));

}

Page 54: Advanced Coded UI Testing

Extract property value from an object (GetPropertyValue)Explore the object and see which property value you can and

want to extractIn this example we will extract the innerText value from the popup object identifying it by searching for the window name

public static class SharedActions

{

public static string GetPropertyValue()

{

WinWindow popUpWindow = new WinWindow();

popUpWindow.SearchProperties[WinWindow.PropertyNames.Name] = "Message from webpage";

WinText innerText = new WinText(popUpWindow);

string text = innerText.DisplayText;

return text;

}

Page 55: Advanced Coded UI Testing

DEMO

Advanced Coded UI

Page 56: Advanced Coded UI Testing

Playback Settings

• In a coded UI test playback, you can instruct a certain test method to work in a different way, for instance• You can postpone the executing of a method until the

involved control will be ready• You can add a delay time between test methods• You can decide which methods will not fail the test even

though they failed and more…

Page 57: Advanced Coded UI Testing

Playback Settings

• Playback is configured by modifying the fields in Playback.Playbacksettings class.• Playback.wait - Make playback wait for certain event or

time• Continue on Error – The engine will continue on to the

next action after an error

Page 58: Advanced Coded UI Testing

Playback.Wait

• WaitForReadyControl()– This waits for the control to be ready to accept mouse/keyboard input.

• WaitForControEnabled() – This waits for the control to be enabled. For example, you can use this wait till the “Next” button of the wizard is enabled

• WaitForControlExisted() – This waits for the control to exist on the UI. For example, you are expecting an error dialog after the application has done the validation of the parameters.

Page 59: Advanced Coded UI Testing

Example of using WaitForControlCondition

Page 60: Advanced Coded UI Testing

Error Handling

• Raise events when an exception occurs during playback• Catch the exception and use PlaybackError Event

[TestMethod]public void CodedUITestMethod1()} Playback.PlaybackError += Playback_PlaybackError;}

void Playback_PlaybackError(object sender, PlaybackErrorEventArgs e){ if (e.Error.Message.Contains("Can't Find")) e.Result = PlaybackErrorOptions.Skip; else e.Result = PlaybackErrorOptions.Retry;{

Page 61: Advanced Coded UI Testing

61

Tips & Tricks

• Manually recording mouse hovers - Ctrl+Shirt+R

• Selecting a hidden control using the keyboard – Ctrl + I

• Coded UI Recorder configuration file - C:\Program Files (x86)\

Microsoft Visual Studio 11.0\Common7\IDE\

CodedUITestBuilder.exe.config

• MaxLevelsForItemContainer

• RecordImplicitHover

• ExcludeProcess

Page 62: Advanced Coded UI Testing

Thank You