I have been writing unit tests using NUnit and Moq with my Silverlight code for some time now. One problem I keep running into has to do with DependencyObjects.
If anything is derived from DependencyObject, then I can’t instantiate it in my test. For instance, MouseEventArgs derives from DependencyObject. If I have code that takes these args, I can’t create the args for several reasons… one of them being that it is a DependencyObject.
As far as I understand, the base constructor of DependencyObject is trying to work with some statics that don’t exist unless the entire Silverlight system is up and running. Any construction of a class that derives from DependencyObject throws an exception. Bummer.
I do not use the Silverlight Unit Test Framework, because it really isn’t unit testing and requires a UI. I run need real, headless unit tests.
Anyways, The best I have come up with is to wrap these objects and give them interfaces like ITimelineMarker and I give them extension methods to do it: timelineMarker.ToInterface(). This works well, and I can mock them out… but I was wondering:
Has anyone come up with a better way to deal with DepencencyObjects in Silverlight Unit Tests?
Why do you have application logic tied directly to SilverLight events and objects? The caveats of trying to test an application’s logic through it’s UI are well known anti-patterns and have given way to patterns that solve this problem in a more effective manner.
Your UI really should only be concerned with UI events and pass any processing to another layer, the only thing then left to test in your UI would be graphical responses (such as when you click a button does a panel slide in from the side), and the only good way to test interactions like that is to actually do the clicking.
Perhaps a more appropriate answer to your question would be that you need to refactor your code to use a patter such as MVC, MVP, or MVVM so that you can test your application logic independently of your UI layer.