对于MVVM模式下的ViewModel层来说,是不应该直接访问OpenFileDialog或者FolderBrowserDialog的,否则VM会变得难以测试。
参考StackOverFlow,对ViewModel进行改造,使OpenFileDialog动作也可以测试。
首先实现接口IIOService
public interface IIOService { string OpenFileDialog(string srcFilter = ""); IList<string> OpenFileDialogMultiselect(string srcFilter = ""); string FolderBrowserDialog(); }
IIOService
在工程中实现该接口IOService
public class IOService : IIOService { public string OpenFileDialog(string srcFilter = "") { var op = new System.Windows.Forms.OpenFileDialog(); op.Filter = srcFilter; if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK) return op.FileName; return ""; } public IList<string> OpenFileDialogMultiselect(string srcFilter = "") { var op = new System.Windows.Forms.OpenFileDialog(); op.Filter = srcFilter; op.Multiselect = true; if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK) return op.FileNames; return new List<string>(); } public string FolderBrowserDialog() { var path = new System.Windows.Forms.FolderBrowserDialog(); var result = path.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) return path.SelectedPath; return string.Empty; } }
IOService
这样就可以在测试的时候给VM注入一个实现该接口的桩对象,进而进行测试啦。
时间: 2024-10-05 15:29:17