Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rx reactive extensions Observeondispatcher unit test error: The current thread has no Dispatcher associated with it

I want to unit test a view model which contains a registration like:

 public SampleViewModel(IUnityContainer container)
    {
...
    Observable.FromEventPattern<PropertyChangedEventArgs>(gridViewModel, "PropertyChanged")
                    .**ObserveOnDispatcher()**
                    .Subscribe(_ => this.Update());
...
}

When I run the unit test it tells me that "The current thread has no Dispatcher associated with it." when reaching this code.

One solution would be to use a Scheduler but I don't want to modify the Viewmodel.

Is there a solution to make the unit test pass this statement without getting an error?

like image 279
Pinte Dani Avatar asked Dec 25 '22 20:12

Pinte Dani


1 Answers

I would suggest that you provide you own IScheduler implementation to ObserveOn(IScheduler) instead of using the ObserveOnDispatcher() operator. I have used techniques for loading a DispatcherFrame or a Dispatcher but the problem is that you are still using a Dispatcher. Eventually I found that you just "fall off the cliff" especially once you have long running background threads involved. Following the guidelines of "No threading in Unit tests" just dont let the dispatcher get near your ViewModels! Your Unit tests will run much, much faster.

A far superior way to deal with this is to inject an interface that gives access to your Dispatcher Scheduler (via the IScheduler interface). This allows you to substitute in an implementation that exposes the TestScheduler. You now can control time in your unit test. You can control and validate which actions are marshalled to each scheduler.

This is a really old (pre-Rx) post on 'Unit' testing WPF with Dispatcher calls from early 2009. It seemed like a good idea at the time.

https://leecampbell.com/2009/02/17/responsive-wpf-user-interfaces-part-5/

More information on Testing with Rx and the TestScheduler is found in my other site on Rx

http://introtorx.com/Content/v1.0.10621.0/16_TestingRx.html

like image 134
Lee Campbell Avatar answered Jan 14 '23 07:01

Lee Campbell