Unit testing with MVVM Light & DispatcherHelper

I have an SL4 application that uses the MVVM Light Toolkit. In the view model, I call the data service, which retrieves data from the OData service. Inside the virtual machine, I use the utility class DispatcherHelper (part of MVVM Light) to update the property on the virtual machine from the data in the callback that I pass to the data service. For example, my model method is as follows:

public string CurrentUserLogin { get { if (string.IsNullOrEmpty(_currentUserLogin)) RetrieveCurrentUserLogin(); return string.IsNullOrEmpty(_currentUserLogin) ? _currentUserLogin : _currentUserLogin.Replace(@"\\", @"\"); } set { if (_currentUserLogin != value) { _currentUserLogin = value; RaisePropertyChanged(CurrentUserLoginPropertyName); } } } private void RetrieveCurrentUserLogin() { DataService.GetCurrentUserLogin(result => { DispatcherHelper.UIDispatcher.BeginInvoke(() => { CurrentUserLogin = result; }); }); } 

And here is what my after-sales service looks like:

 public void GetCurrentUserLogin(Action<string> callback) { // create query request var query = OnDemandContext.CreateQuery<string>("GetCurrentUserLogin"); var request = (HttpWebRequest)WebRequest.Create(query.RequestUri); request.BeginGetResponse(asyncResult => { var responseStream = request.EndGetResponse(asyncResult).GetResponseStream(); var responseDocument = XDocument.Load(responseStream); callback(responseDocument.Root.Value); }, null); } 

Everything works fine when I run my SL application. However, the problem is that I am trying to write unit tests against it using the SL module testing module. I can check my data service without any problems, but it seems that DispatcherHelper throws the key in all my tests, since DispatcherHelper.UIDispatcher is always null at startup. I assume this has something to do with initlization (which is in my SL Application_Startup () application). I tried to initialize it in my test application, but that does not help. I also tried using DispatcherHelper.CheckBeginInvokeOnUI (), but this does not affect the problem.

Ideas?

+4
source share
1 answer

AC

I just created a simple SL UT project and I did it in App.XAML.CS

 private void Application_Startup(object sender, StartupEventArgs e) { RootVisual = UnitTestSystem.CreateTestPage(); DispatcherHelper.Initialize(); } 

Then I install this as a test (in tests.cs):

 [TestMethod] public void TestMethod1() { Assert.IsNotNull(DispatcherHelper.UIDispatcher, "UI Dispatcher should not be null"); DispatcherHelper.CheckBeginInvokeOnUI(() => { // Do nothing var x = 1; }); } 

It worked for me. I even set a breakpoint at "var x = 1;" and he hit the breakpoint. Does this solve your problem? (if so, mark this as an answer).

+4
source

Source: https://habr.com/ru/post/1335880/


All Articles