locked
Unit Testing WPF Command RRS feed

  • Question

  • Hi,

    I am trying to write unit tests for a command that executes an asynchronous action using tasks (TPL). 

    Here is the example code that I am trying to achieve.

    class MainPageViewModel
        {
            private IService service_;
    
            public ICommand StartCommand{get;set;}
    
            //Bind this method to Start Commmand
            private void StartTask()
            {
                var task = service_.StartServiceAsync();
                task.ContinueWith(AfterService);
            }
    
            private void AfterService(Task<IResult> result)
            {
                //update UI with result
            }
        }
    
        class TestClass
        {
            [TestMethod]
            public Test_StartTask()
            {
                MainPageViewModel vm = new MainPageViewModel();
                StartCommand();
                //need to check if UI is updated but since the AfterService is called on a different thread the assert fails
    
            }
        }

    In my Test Method I can't write Assert after the StartTask() call, please help me on how to handle such scenarios for writing test cases? TIA.


    Please mark the replies as answers if they help or unmark if not.

    Friday, February 8, 2013 3:37 PM

Answers

  • I would rework this slightly - if you make your continuation return, you can use that:

    //Bind this method to Start Commmand
    
    private Task StartTask()
    {
        var task = service_.StartServiceAsync();
        // Return the continuation task
        return task.ContinueWith(AfterService, 
          // This probably needs to be on the UI thread...
          TaskScheduler.FromCurrentSynchronizationContext());
    }
    
    private void AfterService(Task<IResult> result)
    {
                //update UI with result
    }

    If you do this, your assert can happen within a continuation instead of trying to write it directly.  If you're using VS 2012, you can have the unit test return a Task, and just await the call then check it.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by Mr. Javaman II Friday, February 8, 2013 5:41 PM
    • Marked as answer by Sri Velicheti Monday, February 11, 2013 3:09 PM
    Friday, February 8, 2013 5:35 PM