How to shim OpenFileDialog.ShowDialog method

大兔子大兔子 提交于 2019-12-11 08:43:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!