Reputation: 35
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.
Upvotes: 1
Views: 130
Reputation: 420
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.
Upvotes: 1