title: How to Unit Test DelegateCommand that calls async methods in MVVM
body: <p>I am new to Unit Testing MVVM and using PRISM on my project. I am implementing Unit Testing on our current project and not having luck finding resources online that would tell me how totest DelegateCommand that calls async method. This is a follow up question to my post - <a href="https://stackoverflow.com/questions/15631635/how-to-unit-test-a-viewmodel-with-async-method">How to Unit Test a ViewModel with async method.</a> on how to unit test an async methods in MVVM and was answered that public methods can be tested using async TestMethod. This scenario will work only if the method that I want to test are public methods.</p>
  
  <p>The problem is I want to test my DelegateCommand as this are the only public details that I want to expose on other classes and everything else are private. I can expose my private methods as public but I will never do this as its a bad design. I am not sure on how to go about this - Is DelegateCommand needs to be tested, or there are some other work around this? I am interested to know how other go about this and somehow lead me to the right path.</p>
  
  <p>Here are my codes again </p>
  
  <pre><code> async void GetTasksAsync()
          {
              this.SimpleTasks.Clear();
              Func&lt;IList&lt;ISimpleTask&gt;&gt; taskAction = () =&gt;
                  {
                      var result = this.dataService.GetTasks();
                      if (token.IsCancellationRequested)
                          return null;
                      return result;
                  };
              IsBusyTreeView = true;
  
              Task&lt;IList&lt;ISimpleTask&gt;&gt; getTasksTask = Task&lt;IList&lt;ISimpleTask&gt;&gt;.Factory.StartNew(taskAction, token);
              var l = await getTasksTask;          // waits for getTasksTask
  
  
              if (l != null)
              {
                  foreach (ISimpleTask t in l)
                  {
                      this.SimpleTasks.Add(t); // adds to ViewModel.SimpleTask
                  }
              }
          }
  </code></pre>
  
  <p>also here is the command in my VM that calls the async method above</p>
  
  <pre><code>  this.GetTasksCommand = new DelegateCommand(this.GetTasks);
        void GetTasks()
          {
                  GetTasksAsync();
          }
  </code></pre>
  
  <p>and now my Test Method goes like </p>
  
  <pre><code> [TestMethod]
          public void Command_Test_GetTasksCommand()
          {
            MyViewModel.GetTaskCommand.Execute(); // this should populate ViewModel.SimpleTask 
            Assert.IsTrue(MyBiewModel.SimpleTask != null)
          } 
  </code></pre>
  
  <p>Currently what I am getting is that my ViewModel.SimpleTask = null this is because it does not wait for the async method to finish.</p>