Question

I have a ViewModel which, in the constructor, makes a call to an async void method to add to a collection

public MyViewModel(ICommandHandler commandHandler)
{
    _commandHandler = commandHandler;
    SetupCollection();
}


private async void SetupCollection()
{
    var commands = GetCommands();

    foreach (var command in commands)
    {
        var response = await _commandHandler.ExecuteGetReply(command);

        if (response != null)
           Response.Add(response);
    }
}

How exactly would I stub the _commandHandler.ExecuteGetReply() command to return a value?

Also, is it OK to have such a function in the constructor to do something like this? Or should this perhaps go within an... override void OnActivate() call (I'm using Caliburn Micro) ?

Was it helpful?

Solution

ICommandHandler.ExecuteGetReply appears to return a Task<Response> so you can do something like:

ICommand commandArg;
Response response;
stubHandler.Stub(h => h.ExecuteGetReply(commandArg)).Return(Task.FromResult(response));

I wouldn't call an async void method from your constructor however, since you will have no way of being notified when it has completed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top