silverlightunit-testingnunitdependencyobject

How do you unit test Silverlight ValueConverters that create DependencyObjects


I have a Silverlight ValueConverter that should take an enum and convert it to a Brush. Something like this simplified example:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var brush = new SolidColorBrush(Colors.Blue);
    var entryType = (EntryType)value;
    if (entryType == EntryType.Hour)
        brush.Color = Colors.Red;
    return (brush);
}

If I want to unit-test this, it won't work. I get this exception:

System.TypeInitializationException : The type initializer for 'MS.Internal.JoltHelper' threw an exception.
----> System.IO.FileNotFoundException : Could not load file or assembly 'System.Xml, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. 
at MS.Internal.JoltHelper.get_ThreadID()
at MS.Internal.XcpImports.CheckThread()
at System.Windows.DependencyObject..ctor(UInt32 nativeTypeIndex, IntPtr constructDO)
...

I know this is because in my (NUnit) unittests, a different CLR is loaded than when my Silverlight application would run. I know I shouldn't test UI in unit-tests, but this is just testing my ValueConverter, so I think it is a valid test.

Does anyone know if and how this is testable?


Solution

  • I think the main problem here is that you are trying to run Silverlight code in a non-Silverlight runtime.

    Either yesterday or the day before I wrote a ValueConverter that does much the same as yours. I also wrote some tests for it. I ran the tests using the Silverlight unit test runner that comes with the Silverlight Toolkit, and the tests all ran fine.

    I'd recommend running your Silverlight tests in a Silverlight runtime, i.e. within the browser plugin. You can use the Silverlight unit test framework I mentioned above, and there is also a port of NUnit to Silverlight which you might like to try. However, I don't know how up-to-date this Silverlight NUnit port is.