简体   繁体   中英

Unit testing DelegateCommand using Rhino Mock

I am trying to unit test a command execution for a command that displays a dialog, however I keep getting NullReferenceException and I do not know why. Any suggestion would be appreciated.

The viewmodel being used by view snippet:

public class ConvertFileDialogViewModel:IConvertFileDialogViewModel
{
    private string _inputFolderPath;

    public DelegateCommand SelectInputFolderCommand { get;set; }
        
    public ConvertFileDialogViewModel()
    {
        SelectInputFolderCommand = new DelegateCommand(SelectInputFolderDialog);
    }

    public string InputFolderPath
    {
        get => _inputFolderPath;
        set
        {
            _inputFolderPath = value;
            OnPropertyChanged(nameof(InputFolderPath));
        }
    }
        

    public void SelectInputFolderDialog()
    {
        using (var fbd = new FolderBrowserDialog())
        {
            DialogResult result = fbd.ShowDialog();

            if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
            {
                InputFolderPath = fbd.SelectedPath;
            }
        }
    }
}    

Interface snippet:

public interface IConvertInterviewDialogViewModel
{
    string InputFolderPath { get; set; }
    DelegateCommand SelectInputFolderCommand { get;set; }
    
}

Unit-Test snippet:

[TestMethod]
public void SelectInputFolderCommandTest()
{
    var model = MockRepository.GenerateMock<IConvertFileDialogViewModel>();
    model.SelectInputFolderCommand.Execute();
    model.AssertWasCalled(vm=>vm.SelectInputFolderCommand);
}

Error:

ConvertInterviewDialogViewModelTests.SelectInputFolderCommandTest threw exception: System.NullReferenceException: Object reference not set to an instance of an object.

I have never used Rhino Mocks, but what I can infer from

var model = MockRepository.GenerateMock<IConvertFileDialogViewModel>();

is that you create a mock of an interface, that will not call the constructor of ConvertFileDialogViewModel , thus the SelectInputFolderCommand property will remain null .

Edit :
As Nkosi correctly pointed out, you can't use the command of your ViewModel, as it would invoke a dialog, which you can't unit test.
Thus, you need to initialize the SelectInputFolderCommand property after creating the mock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM