views:

305

answers:

2

I have a windows phone 7 silverlight app that I'm trying to unit test. My tests fail with the following error:

System.DivideByZeroException : Attempted to divide by zero.

On the following line:

Deployment.Current.Dispatcher.BeginInvoke(() => RaisePropertyChanged("Lat"));

I assume this is because there is no ui thread. Do I need to abstract the BeginInvoke calls so they can be mocked in my test?

Update:

I ended up abstracting so I could mock in the unit test. Works great. What do you think?

public class UiDispatcher : IUiDispatcher
{
    public void InvokeOnUiThread(Action action)
    {
        Deployment.Current.Dispatcher.BeginInvoke(action);
    }
}
A: 

Although I haven't tried to do this myself, I'll bet that the DispatcherHelper class from the MVVM Light framework would do that for you as well. I've not tried it in the context of unit tests, but I've inadvertantly called out to DispatcherHelper from the UI thread and it seemed to work OK.

The MVVM Light toolkit is available from Laurent Bugnion at http://mvvmlight.codeplex.com/, and you can see my most recent exploration of WP7 and MVVM on my blog at http://chriskoenig.net/series/wp7.

HTH!
Chris

Chris Koenig
+1  A: 

You've got it. You might want to add a Dispatcher.CheckAccess() conditional as well, which can save you from an Invoke if you don't need it:

public void InvokeOnUiThread(Action action) 
{
    if(Deployment.Current.Dispatcher.CheckAccess())
    {
        action();
    } else {
        Deployment.Current.Dispatcher.BeginInvoke(action);
    }
} 
Ben Gracewood