mardi 26 avril 2016

Patterns for testing ICommand that call async methods

I am just looking at best practices for unit testing (NUnit) ICommand and specifically the MvxCommand implementation within MVVMCross

View Model

Command

public ICommand GetAuthorisationCommand
{
    get { return new MvxCommand(
            async () => await GetAuthorisationToken(),
            () => !string.IsNullOrWhiteSpace(UserName) && !string.IsNullOrWhiteSpace(Password)); }
}

Method

private async Task GetAuthorisationToken()
{
    ...Do something async
}

Unit Test

    [Test]
    public async Task DoLogonCommandTest()
    {
        //Arrange
        ViewModel vm = new ViewModel(clubCache, authorisationCache, authorisationService);

        //Act
        await Task.Run(() => vm.GetAuthorisationToken.Execute(null));

        //Assert
        Assert.Greater(MockDispatcher.Requests.Count, 0);
    }

Now the problem I have is that the tests drop through with out awaiting the async operations and this feels a little hacky in calling the async method from the ICommand.

Are there any best practices in unit testing these kind of ICommands and async methods?

Aucun commentaire:

Enregistrer un commentaire