Search code examples
c#unit-testingasync-await.net-4.5prism-5

Unit Test Prism 5 async Delegatecommand executes in parallel


I am writing a unit test for a ViewModel which has a DelegateCommand. This command uses an async method for execution, which is supported since Prism 5 like this:

MyCommand = new DelegateCommand(async () => await MyMethod());

Now I have my unit test and I notice, that

await model.Command.Execute();
Assert.IsTrue(model.CommandWasRun); // just an example

immediately returns (and therefore fails), while the command is run.

The reason I think, that this is a bug, is that in the same unit test everything is fine, if I write

await model.MyMethod();
Assert.IsTrue(model.CommandWasRun);

Am I missing something or is this a bug?


Solution

  • You cannot use an async delegate in the DelegateCommand constructor. You have to use FromAsyncHandler:

    MyCommand = DelegateCommand.FromAsyncHandler(async () => await MyMethod());
    

    or, equivalently:

    MyCommand = DelegateCommand.FromAsyncHandler(() => MyMethod());