SilverUnit
Things to notice in the examples:
- Tests can be run with the regular NUnit or MS Test tools. No need for specialized Silverlight-based compilation.
- Objects under test can still be part of a Silverlight Assembly (in the examples, these are the Silverlight Toolkit Controls)
- We simply "new" up objects under test. But the tests can be run in the regular CLR runtime, not in silverlight.
- Tests do not run in the browser - they are fully in memory
- Tests do no invoke the silverlight runtime, due to the use of the "SilverlightUnitTest" attribute
In C#
[Test,SilverlightUnitTest]
public void SetProperty()
{
var box = new AutoCompleteBox();
box.MinimumPrefixLength = -3;
int length = (int) box.MinimumPrefixLength;
Assert.AreEqual(-1, length);
}
[Test,SilverlightUnitTest]
public void SetChildTemplate()
{
//arrange
var box = new AutoCompleteBox();
//injecting our child controls into the parent control without needing XAML
SilverUnit.SetTemplateChild(box, "Text", new TextBox());
SilverUnit.SetTemplateChild(box, "Popup", new Popup());
SilverUnit.SetTemplateChild(box, "SelectionAdapter", new ListBox());
SilverUnit.SetTemplateChild(box, "DropDownToggle", new ToggleButton());
//act
box.OnApplyTemplate(); //full control of when to call OnApplyTemplate
//assert
SilverUnit.Assert.VisualStatedWasChangedTo("Normal",box,false); //special SilverUnit Assert to check moving to a Visual State
}
In VB.NET
//it's easy to trigger control events on any control using special extension methods
<SilverlightUnitTest(), Test()> _
Public Sub SetTextBox_SetTextOnTextBox_ACBoxIsUpdated()
Dim txt As TextBox = New TextBox()
Dim box As AutoCompleteBox = New AutoCompleteBox()
txt.SelectionStart = 0
txt.SelectionLength = 0
txt.IsEnabled = True
txt.Focus()
box.TextBox = txt
txt.Text = "a"
txt.FireEvent(Events.TextChanged, Me, FakeInstance(Of TextChangedEventArgs)) //here we also are able to send in fake event args
Assert.AreEqual("a", box.Text)
Assert.AreEqual(box.Text, txt.Text)
End Sub