简体   繁体   中英

How do i Unit Test my RelayCommand using Moq?

I have a RelayCommand Class which implements the ICommand interface and it takes a new Action as the parameter for its constructor. It is pretty basic

For example here is how i use command when a button is clicked. And this code is in the constructor of my ViewModel.

All this code does is opens a FolderBrowserDialog and lets the user select a folder.

OutputSelect = new RelayCommand(new Action<object>(folderSelect));

This is a method in the viewModel class

public void folderSelect(object obj)
        {
            var dlg = new FolderBrowserDialog();


            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                // Open document             
                string filename = dlg.SelectedPath;
                _model.OutputFolder = filename;
            }
        }

Once the button is clicked the method folderSelect is run.

Now I am wondering how do I unit test this feature of my Application?

Do i make a Mock for a Action and pass that into my viewModel.OutputSelect.Execute()?

"Model View ViewModel" is an architectural pattern and which give us clear separation between User interface layer (UI) to Business Layer. The Button Command Property is of ICommand Type and behind the scenes when user click on the Button it called ICommand.Execute() method.

So, to do unit testing you can do this by direct calling of Execute(object parameter) method In you case it is

OutputSelect.Execute(null)

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