Unit test MVVM commands

1.9k views Asked by At

I have a new WPF MVVM project and would like to write "some useful" unit tests for my ViewModel.

My ViewModel class:

public class ConsignorViewModel : ViewModel
{
    ...
    #region Commands
    void NewModel()
    {
        _model = new Consignor();

        RaisePropertyChanged(String.Empty, validatePropertyName: false);
    }
    void SaveModel()
    {
        ... //some logic to save
    }

    public override ICommand New { get { return new RelayCommand(NewModel); } }
    public override ICommand Save { get { return new RelayCommand(SaveModel); } }
    #endregion
}

I would like to unit test those commands. What is the best way to do so?

At the moment my unit test method just looks like this:

[TestMethod]
public void TestCommands()
{
    //Arrange

    //Act

    //Assert
    ////New Command
    Assert.IsNotNull(_consignorViewModel.New);
    Assert.IsTrue(_consignorViewModel.New is RelayCommand);

    ////Save Command
    Assert.IsNotNull(_consignorViewModel.Save);
    Assert.IsTrue(_consignorViewModel.Save is RelayCommand);
}

I would like to test the behaviour/result of an command. When testing the "new" command I would like to ensure that the model is "reset" (constructor call). At the moment this is not possible as my methods "NewModel" and "SaveModel" are not visible in the unit test which is correct as they're not part of the public interface. So I don't want to make them public ...

1

There are 1 answers

3
k.m On BEST ANSWER

At the moment this is not possible as my methods "NewModel" and "SaveModel" are not visible in the unit test which is correct as they're not part of the public interface.

And they shouldn't be. You already know the solution to this problem, you even said it yourself:

I would like to test the behaviour/result of an command.

That's the point. With unit tests we verify observable effects. How does the user recognise that model has been reset? User has no knowledge of New method, nor should unit test. If New method has no obeservable side effect, visible from public POV, then you might just as well remove it from your code base.

Identify those publicly visible changes and test against them.