Retrieving Text from a .NET ListBox Control using the MUIA Library

I ran into an interesting technical riddle yesterday. I was writing some demonstration UI test automation for a class which is part of a new Certificate in Software Testing with Microsoft Technologies program. My application under test is a .NET Windows application that plays a hypothetical game of two-card poker. I was using the Microsoft UI Automation library to implement my UI test automation. Everything went according to plan until I decided I’d like to examine the contents of a ListBox control as part of the process of determining the final state of the app under test (in order to determine a pass/fail result). It turns out that there are no existing published examples of how to do this. I spent a couple of hours but finally came up with the correct approach. See the screenshot below.
In words, first get a reference to the ListBox control itself. Next get a reference to that control’s ListItem collection. Next use zero-based array indexing to get a reference to a particular item in the collection. And then use the Name property of that item to get the text. The trick is the last step. I had been trying to use the MUIA TextPattern and ValuePattern patterns. It turns out that the Name property of a ListItem item reflects the text contents. So, the code to fetch the contents of a .NET ListBox control using the MUIA library resembles the following:
AutomationElement aeListBox =
  new PropertyCondition(AutomationElement.ControlTypeProperty,
AutomationElementCollection aeListBoxItems =
  new PropertyCondition(AutomationElement.ControlTypeProperty,
AutomationElement aeFirstItem =
string s =
Anyway, like always, the answer seems obvious once you know it. I believe that the MUIA library will become the de facto standard technology for UI test automation of Microsoft programs, once all the little recipes like the one I’ve presented here become well known.
This entry was posted in Software Test Automation. Bookmark the permalink.