问题
I have a WPF ViewModel, that has a command which opens a File dialog like this:
var dlg = new OpenFileDialog();
var result = dlg.ShowDialog();
Now I would like to unit test that command. ShowDialog is a method inherited from the CommonDialog, so I assumed I can shim it like this:
Microsoft.Win32.Fakes.ShimCommonDialog.AllInstances.ShowDialog = () => true;
but I'm getting the following compilation error:
Delegate
Microsoft.QualityTools.Testing.Fakes.FakesDelegates.Func<Microsoft.Win32.CommonDialog,bool?>
does not take 0 arguments
Any ideas?
回答1:
The below code would achieve what you need.
System Under Test (SUT)
public class Sut
{
public bool SomeMethod()
{
var dlg = new OpenFileDialog();
var result = dlg.ShowDialog();
return result.Value;
}
}
Unit Test (using MS Fakes)
using System;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Win32.Fakes;
using WpfApplication1;
[TestMethod]
public void SomeTest()
{
using (var context = ShimsContext.Create())
{
Nullable<bool> b2 = true;
ShimCommonDialog.AllInstances.ShowDialog = (x) => b2;
var sut = new Sut();
var r = sut.SomeMethod();
Assert.IsTrue(r);
}
}
Note that you need to have the PresentationFramework.4.0.0.0.Fakes assembly as well as the correct additional Fakes assemblies in your test.
来源:https://stackoverflow.com/questions/20586386/how-to-shim-openfiledialog-showdialog-method