eL-Prova
eL-Prova

Reputation: 1094

Mvvmcross unittest for InvokeOnMainThread

I have in my init of the viewmodel the follow code:

public void Init(int id)
{
   Task.Run(() => {
        var loadedObjects = service.GetAllById(id);
        InvokeOnMainThread(() => {
           foreach(var objectA in loadedObjects)
           {
              Items.Add(objectA);
           }
        });
   }
}

My tests is like this:

[Test]
public void ShouldTest()
{
   //For additional Setup of MvvmCross and registering of Dispatcher
   Setup();

   var viewModel = new ViewModelObjects();
   viewModel.Init(1);

   Assert.AreEqual(1, viewModel.Items.Count);
}

When I run my test the assert is running first after that the InvokeOnMainThread is called. My unit has a dispatcher (From: https://github.com/MvvmCross/MvvmCross/wiki/Testing)

  1. Reason for Task.Run is rest of GUI needs to be rendered.
  2. InvokeOnMainThread triggers the ProperyChanged
  3. Tries like (http://www.damirscorner.com/blog/posts/20140324-HandlingPropertyChangedEventInMvvmCrossViewModelUnitTests.html) didnt work

Any idea how i can test the Items?

Upvotes: 0

Views: 168

Answers (1)

Cheesebaron
Cheesebaron

Reputation: 24460

Task.Run without an await just continues execution of the code. So what you see in your Items collection, might not be what you expect as the code inside of the expression body in the Task.Run probably hasn't finished executing.

This is not really a MvvmCross issue. However a general threading issue.

I suggest that you use InitAsync instead, and await the method. Your tests can be async too.

Upvotes: 1

Related Questions