Get Element Properties In UITest In Xamarin

When doing UI Automation with Xamarin UITest, you can easily find elements, tap on them and get their basic values, such as Size, and Text. If we want to find out more information on an element, we need to invoke the platform specific property or method on the element we are referencing.

Invoking A Native Method

In this example, I will be getting the color of a label, or more specifically a TextView or UILabel.

In Android, we can get the color, by invoking the get_CurrentTextColor method. If there are properties on the Android element, that you want, just prefix it with get_ to get the native naming, as in C# you will just see it as a CurrentTextColor property.

var colorValue = App.Query(x => x.Id("ElementId").Invoke("getCurrentTextColor"))[0];

For iOS, there is just the TextColor property that we can get.

var colorValue = App.Query(x => x.Id("ElementId").Invoke("textColor"))[0];

But now there is normally a problem, in that these return native objects, and you don’t have access to these types.

Converting Values

Now that we have an object, we need to convert them. In this example, Android is returning an int, but I want to convert this to an RGB. To do this, we can just convert it as such.

int color = Convert.ToInt32(colorValue); 
int r = (color >> 16) & 0xFF; 
int g = (color >> 8) & 0xFF; 
int b = (color >> 0) & 0xFF; 

var rgb = $"{r.ToString("X").PadLeft(2, '0')}{g.ToString("X").PadLeft(2, '0')}{b.ToString("X").PadLeft(2, '0')}";

iOS, is a little trickier, because it returns a UIColor object. ToString, will normally spill out some good information, but there is a slightly easier way. UIColor has a private field called styleString. Because this is never deployed to the App Store, and is just an automation test, we have the luxury of accessing these fields. We can access it as such.

var colorValue = App.Query(x => x.Id("ElementId").Invoke("textColor").Invoke("styleString"))[0];

Notice that we can keep invoking methods, off returned objects. This returns a string RGB value. From here we can just parse it, to receive the int values, and convert to a hex RGB string.

// e.g. rgb(53,76,193)
colorValue = colorValue.Substring(4).TrimEnd(')');

var values = colorValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

int r = Convert.ToInt32(values[0]);
int g = Convert.ToInt32(values[1]);
int b = Convert.ToInt32(values[2]);

var rgb = $"{r.ToString("X").PadLeft(2, '0')}{g.ToString("X").PadLeft(2, '0')}{b.ToString("X").PadLeft(2, '0')}";
Microsoft MVP | Xamarin MVP | Xamarin Certified Developer |
Exrin MVVM Framework | Xamarin Forms Developer | Melbourne, Australia

Related Posts


Leave A Comment?