The Caliburn.Testability assembly contains various classes related to unit testing a UI. You can use the BindingValidator to validate data bindings on DependencyObjects, DataTemplates and Styles. The easiest way to access this functionality is through the static Validator class. It has several methods for the most common scenarios related to unit testing data bindings.
Note: This feature of Caliburn is only available to WPF due to limitations in the Silverlight API. It is not in the Alpha download but can be found in the Trunk.
Here is an example of a simple unit test:
[TestFixture]
public class The_UI_for_adding_a_new_customer
{
[Test]
public void is_data_bound_to_a_CustomerModel()
{
var validator = Validator.For<AddNewCustomerForm, CustomerModel>();
var result = validator.Validate();
Assert.That(result.HasErrors, Is.False, result.ErrorSummary);
}
}
The Validator class has several 'For' methods. In this case, we are using the overload that takes a type parameter for the UI and a type parameter for the bound data type. Simply call the Validate method and check the results to insure that all your binding expressions are correct. The ErrorSummary contains a textual representation of any errors that are found. The framework will walk the entire UI hierarchy checking data bindings on all dependency properties. It will check all elements for inline DataTemplates (such as ItemsControl.ItemTemplate) and, if found, check the template. All inline styles will be checked. Triggers on both DataTemplate and Style will also be checked.
You can also validate the presence of a specific property:
[TestFixture]
public class The_UI_for_adding_a_new_customer
{
[Test]
public void is_data_bound_to_the_CustomerModel_FirstName()
{
var validator = Validator.For<AddNewCustomerForm, CustomerModel>();
var result = validator.Validate();
Assert.That(result.WasBoundTo(x => x.FirstName));
}
}
By using the WasBoundTo method, a test can use lambda expressions to do strongly typed validation of specific properties. There is also a WasNotBoundTo method for convenience purposes.
Validation of items in resource dictionaries is also easy:
[TestFixture]
public class The_UI_for_adding_a_new_customer
{
[Test]
public void is_data_bound_to_a_CustomerModel()
{
var validator = Validator.For<MyResources, CustomerModel>("addNewCustomerTemplate");
var result = validator.Validate();
Assert.That(result.HasErrors, Is.False, result.ErrorSummary);
}
}
In the above example, the validator creates the ResourceDictionary called MyResources and then locates the resource with key "addNewCustomerTemplate." It then determines whether the resource is a DataTemplate, Style or DependencyObject and runs the appropriate validation.
Posted
10-25-2008 9:38 AM
by
Rob Eisenberg