Wednesday, April 15, 2009

Silverlight Automated UI Testing

Working with alot of larger clients at IdentityMine we frequently work with teams that use automated testing and deployment systems. I did a post last year on deployment with msbuild and build environment deployments etc and today I'd like todo a quick post on wiring up a Silverlight application for automated UI testing. This is a great way to tied into existing test structures but keep in mind there is a Unit test framework off MSDN that is a great place to start.

http://code.msdn.microsoft.com/silverlightut/

and

http://weblogs.asp.net/scottgu/archive/2008/04/02/unit-testing-with-silverlight.aspx

So quick and dirty this method is kind of a hack to expose bits to existing web testing systems that can only talk to the DOM. with that... I'm going to focus on showing you alot of code...

To start with we have this simple application using this xaml keeping in mind I excluded the extrensous stuff...

<grid>
<grid.columndefinitions>
<columndefinition>
<columndefinition>
<columndefinition>
</Grid.ColumnDefinitions>
<textbox name="inputhere" height="30">
<button name="Btn1" content="process input" click="Button_Click" column="1" height="30">
<textbox name="Output" height="30" column="2">
</grid>

and in the code we add the following C#


private string ProcessString = "complete with [{0}]";

private void Button_Click(object sender, RoutedEventArgs e)
{
Output.Text = string.Format(ProcessString, inputhere.Text);
}

this works great but pretend it is much more complicated... So then we add the following code to our code behind...:

[ScriptableMember]
public void SetTextField(String InputValue)
{
inputhere.Text = InputValue;
}

[ScriptableMember]
public void ClickButton()
{
Button_Click(new object(), null);
}

[ScriptableMember]
public string GetValue()
{
return Output.Text;
}

and then we add the following to our page constructor:


HtmlPage.RegisterScriptableObject("MainPage", this);

and we add this #include er I mean 'using' statement:

using System.Windows.Browser;

from here we have exposed the key elements so any testing system that can talk to the Browser DOM can then wire up to what appear at JavaScript objects like this:

//simulates input:
top.document.getElementById('Silverlight1').content.MainPage.SetTextField("test");

// simulates a click
top.document.getElementById('Silverlight1').content.MainPage.ClickButton();


//gets a value.
alert( top.document.getElementById('Silverlight1').content.MainPage.GetValue() );

I know quick and dirty but now our automated UI web app infrastructure can 'test' our Silverlight application easily.