Unit test the ICommand Property of ViewModel – MVVM Pattern

Good to have new Patterns to design your applications. MVVM is such one pattern.

I assume the reader of this post has basic understanding of what MVVM stands for.

MVVM gives the flexibility to handle the User action in ViewModel using ICommand property. However this brings another challenge for developer of unit test this.

Consider a sample ICommand:

public ICommand ClearCommand
{
            get
            {
                if (this.infClearCommand == null)
                {
                    this.infClearCommand = new RelayCommand(
                        param =>
                        {
                            this.SelectedFileName = string.Empty;
                            this.infFileReader = null;
                            this.NotifyPropertyChanged("SelectedFileName");
                        },
                        param =>
                        {
                             return true;
                         });
                 }
                 return this.infClearCommand;             
        }         
}

Now to unit test this piece of code:

[TestMethod]
public void Test()
{
    ABCViewModel target = new ABCViewModel(); 
    target.SelectedFileName = "XYZ";
    target.ClearCommand.Execute(null);
    Assert.AreEqual(target.SelectedFileName, string.Empty);
}

ICommand.Execute will take care of the Unit Test for you.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s