Introduction to UI Unit Testing with UI Automation - Verifying Commands (
Page 5 of 8 )
The Edit menu contains commands that can alter the text, so the next unit test verifies the functionality of these commands. When retrieving the elements for the menu items, the menu needs to be expanded so that these items are generated and available. Menu items can support different control patterns; in this case, we need to use the Expand Collapse pattern to expand and collapse the Edit menu; the menu items under the Edit menu support the Invoke pattern.
[TestMethod()]
public void EditMenuTest()
{
// Retrieve Edit menu element
AutomationElement menuElement = FindElement(AppElement,
AutomationElement.AutomationIdProperty, "Edit");
// Expand the menu to generate menu items
ExpandCollapsePattern menuPattern = GetPattern(menuElement,
ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
menuPattern.Expand();
AutomationElement cutElement = FindElement(menuElement,
AutomationElement.AutomationIdProperty, "Cut");
...
menuPattern.Collapse();
// Retrieve the text element
AutomationElement textBoxElement = FindElement(AppElement,
AutomationElement.AutomationIdProperty, "TextBox");
// Retrieve Invoke patterns for the Edit menu items
InvokePattern cutPattern = GetPattern(cutElement,
InvokePattern.Pattern)
as InvokePattern;
...
// Retrieve Text pattern for the text control
TextPattern textPattern = GetPattern(textBoxElement,
TextPattern.Pattern)
as TextPattern;
// Make sure that the text control has focus before modifying the text
textBoxElement.SetFocus();
// Set the initial text in the control
Thread.Sleep(100);
SendKeys.SendWait("^{HOME}");
SendKeys.SendWait("^+{END}");
SendKeys.SendWait("{DEL}");
SendKeys.SendWait(SampleText);
Assert.AreEqual<string>(SampleText, textPattern.DocumentRange.GetText(-1));
// Validate that the Undo and Redo menu items work properly
Thread.Sleep(100);
undoPattern.Invoke();
Assert.AreEqual<string>("", textPattern.DocumentRange.GetText(-1));
redoPattern.Invoke();
Assert.AreEqual<string>(SampleText,
textPattern.DocumentRange.GetText(-1).ToLower));
// Validate that the Copy and Paste menu items work properly
Thread.Sleep(100);
SendKeys.SendWait("^{END}");
SendKeys.SendWait("+{LEFT}+{LEFT}+{LEFT}");
copyPattern.Invoke();
SendKeys.SendWait("^{HOME}");
pastePattern.Invoke();
Assert.AreEqual<string>(SampleText.Substring(
SampleText.Length - 3) + SampleText,
textPattern.DocumentRange.GetText(-1).ToLower());
// Validate that the Cut and Paste menu items work properly
Thread.Sleep(100);
SendKeys.SendWait("^{HOME}");
SendKeys.SendWait("+{RIGHT}+{RIGHT}+{RIGHT}");
cutPattern.Invoke();
SendKeys.SendWait("^{END}");
pastePattern.Invoke();
Assert.AreEqual<string>(SampleText + SampleText.Substring(
SampleText.Length - 3),
textPattern.DocumentRange.GetText(-1).ToLower());
}