Using the WPF Dispatcher in unit tests

前端 未结 16 2172
北恋
北恋 2020-11-27 02:48

I\'m having trouble getting the Dispatcher to run a delegate I\'m passing to it when unit testing. Everything works fine when I\'m running the program, but, during a unit te

16条回答
  •  盖世英雄少女心
    2020-11-27 03:26

    You can unit test using a dispatcher, you just need to use the DispatcherFrame. Here is an example of one of my unit tests that uses the DispatcherFrame to force the dispatcher queue to execute.

    [TestMethod]
    public void DomainCollection_AddDomainObjectFromWorkerThread()
    {
     Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
     DispatcherFrame frame = new DispatcherFrame();
     IDomainCollectionMetaData domainCollectionMetaData = this.GenerateIDomainCollectionMetaData();
     IDomainObject parentDomainObject = MockRepository.GenerateMock();
     DomainCollection sut = new DomainCollection(dispatcher, domainCollectionMetaData, parentDomainObject);
    
     IDomainObject domainObject = MockRepository.GenerateMock();
    
     sut.SetAsLoaded();
     bool raisedCollectionChanged = false;
     sut.ObservableCollection.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e)
     {
      raisedCollectionChanged = true;
      Assert.IsTrue(e.Action == NotifyCollectionChangedAction.Add, "The action was not add.");
      Assert.IsTrue(e.NewStartingIndex == 0, "NewStartingIndex was not 0.");
      Assert.IsTrue(e.NewItems[0] == domainObject, "NewItems not include added domain object.");
      Assert.IsTrue(e.OldItems == null, "OldItems was not null.");
      Assert.IsTrue(e.OldStartingIndex == -1, "OldStartingIndex was not -1.");
      frame.Continue = false;
     };
    
     WorkerDelegate worker = new WorkerDelegate(delegate(DomainCollection domainCollection)
      {
       domainCollection.Add(domainObject);
      });
     IAsyncResult ar = worker.BeginInvoke(sut, null, null);
     worker.EndInvoke(ar);
     Dispatcher.PushFrame(frame);
     Assert.IsTrue(raisedCollectionChanged, "CollectionChanged event not raised.");
    }
    

    I found out about it here.

提交回复
热议问题