Reputation: 1094
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)
Any idea how i can test the Items?
Upvotes: 0
Views: 168
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