Wednesday, January 09, 2008

UIAutomation - testing Calculator

I recently discovered that the UIAutomation library provided in .NET 3.0 doesn't only work for managed code but for any code.

Should you so be inclined, here's how to test that calc.exe provided by Windows in fact can calculate 2+2 correctly.

        [TestMethod]
public void TestAddTwoAndTwo() {

Process calc = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"c:\windows\system32\calc.exe";
calc.StartInfo = startInfo;
calc.Start();
Thread.Sleep(500);

AutomationElement window = AutomationElement.FromHandle(calc.MainWindowHandle);
AutomationElement twoButton = FindAutomationElementByName(window, "2");
AutomationElement plusButton = FindAutomationElementByName(window, "+");
AutomationElement equalsButton = FindAutomationElementByName(window, "=");

AutomationElement editField = window.FindFirst(TreeScope.Descendants, new AndCondition(
new PropertyCondition(AutomationElement.ClassNameProperty, "Edit"),
new PropertyCondition(AutomationElement.IsValuePatternAvailableProperty, true)));
calc.WaitForInputIdle();

InvokePattern clickTwo = twoButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
InvokePattern clickEquals = equalsButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
InvokePattern clickPlus = plusButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;

clickTwo.Invoke();

clickPlus.Invoke();

clickTwo.Invoke();

clickEquals.Invoke();
ValuePattern pattern = editField.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;

Assert.AreEqual(4, int.Parse(pattern.Current.Value,NumberStyles.AllowDecimalPoint|NumberStyles.AllowTrailingWhite));
}
        public AutomationElement FindAutomationElementByName(AutomationElement parent, string name) {
Condition c = new PropertyCondition(AutomationElement.NameProperty, name);
return parent.FindFirst(TreeScope.Descendants, c);
}


You'll also want a reference to UIAutomationClient.dll and the following using:

using System.Windows.Automation;

To find out what the application under test has eaten i.e. how to automate it, do use UISpy.exe provided with the Windows SDK .


And yes, the syntax is a tad verbose ...

1 comment:

Anonymous said...

Nice example! I to used to do tests with UIAutoamtion but moved to a test automation framework called TAFX (which uses UIAutomation among other things...). I did this mainly because I liked the syntax of the tests better. You can check out how the calculator test looks with the TestAutomationFX framework syntax at the screenshot page at http://www.testautomationfx.com .

The framework is in beta but it works pretty ok with many of our tests.

Regards

Tom