MVVM light Dispatcher unit tests

后端 未结 1 720
执笔经年
执笔经年 2021-01-23 20:27

I have the following function

 public void Reset()
 {
     DisableModule();
     DispatcherHelper.UIDispatcher.Invoke(() =>
     {
           PixelPointInfoCo         


        
相关标签:
1条回答
  • 2021-01-23 20:49

    Unfortunately situation is as a result of an initial design issue which made the code base difficult to unit test. The difficulty in creating unit tests for code is directly related to how well the code is designed. The article you mentioned in your post is what you would need to do to make accessing the dispatcher mock-able as it (the dispatcher) is an implementation concern associated with the UI thread which will not be available during your unit tests. Hence the lock on Invoke

    To quote the article you mentioned:

    We are unable to test the code that uses App.Current.Dispatcher (since App.Current will be null during unit tests execution).

    A possible solution would be to create an interface IDispatcher and a wrapper around App.Current.Dispatcher that implements that interface.

    public interface IDispatcher {
        void Invoke(Action action);
        void BeginInvoke(Action action);
    }
    
    public class DispatcherWrapper : IDispatcher {
        Dispatcher dispatcher;
    
        public DispatcherWrapper() {    
            dispatcher = Application.Current.Dispatcher;        
        }
        public void Invoke(Action action) {
            dispatcher.Invoke(action);
        }
    
        public void BeginInvoke(Action action) {
            dispatcher.BeginInvoke(action);
        }
    }
    
    0 讨论(0)
提交回复
热议问题