SilverLight Unit Test for Value Converter
When writing unit tests for the Silverlight application, its
important to write the unit test for the value converters so that you
could test whether converters are working fine or not as Value
Converters are most commonly used in Silverlight applications.
IValueConverter
interface exposes two methods Convert & ConvertBack which are
private by default and one can't call these methods explicitly in any
other class. Neither you can write public wrappers on the Convert and
ConvertBack methods as we can't explicitly call these methods. So we
need some type of workaround to test the Value Converters.
Here is what we will have to do is;
Create a new class which implements the INotifyPropertyChanged Interface and contains a single property. This class's object we will use to test the converter as shown below
public class TestValue : INotifyPropertyChanged
{
private string _value = string.Empty;
public string Value
{
get
{
return _value;
}
set
{
_value = value;
NotifyPropertyChanged("Value");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
#endregion
}
Next we will write a test case to test the value converters by dynamically creating a new TextBox and binding it to the object of the above class as shown below;
[TestMethod]
[Tag("DateFormatter")]
public void Test_DateConverter()
{
TestValue val = new TestValue();
//DateFormatter f = new DateFormatter();
Binding binding = new Binding();
binding.Converter = (IValueConverter)new DateFormatter();
binding.Source = val;
binding.Mode = BindingMode.TwoWay;
PropertyPath propPath = new PropertyPath("Value");
binding.Path = propPath;
TextBox txtBox = new TextBox();
txtBox.SetBinding(TextBox.TextProperty, binding);
// Test Convert
val.Value = "1900/01/01";
Assert.IsTrue(String.IsNullOrEmpty(txtBox.Text));
val.Value = "01/01/2000 00:01:01";
Assert.IsTrue(String.Compare("1/1/2000", txtBox.Text, StringComparison.CurrentCultureIgnoreCase) == 0);
val.Value = "12/01/2000";
Assert.IsTrue(String.Compare("12/1/2000", txtBox.Text, StringComparison.CurrentCultureIgnoreCase) == 0);
// Test ConvertBack
txtBox.Text = "01/01/2001";
Assert.IsTrue(Convert.ToDateTime(txtBox.Text).Equals(Convert.ToDateTime(val.Value)));
txtBox.Text = "09/09/2002";
Assert.IsTrue(Convert.ToDateTime(txtBox.Text).Equals(Convert.ToDateTime(val.Value)));
}
Above is self explanatory code which test the Convert & ConvertBack methods of the Value Converter.. CHEERS :)