使用Moq模拟使用可选参数的方法 [英] Mocking a Method that uses an Optional Parameter using Moq

查看:105
本文介绍了使用Moq模拟使用可选参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下界面的消息框服务

I have a message box service that hase the following interface

public interface IMessageBoxService
{
    DialogResult DisplayMessage(IWin32Window owner, string text,
        string caption, MessageBoxButtons buttons, MessageBoxIcon icon,
        MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button1);
}

它基本上包装了System.Windows.Forms消息框,并允许我模拟显示消息框的代码部分.现在,我有一个用于文本文档的搜索服务,如果搜索循环,该服务将显示不再定位"消息.我想为此类的功能编写单元测试,FindNextMethod

It essentally wraps the System.Windows.Forms message box and allows me to Mock parts of my code that show a message box. Now I have a search service for text documents that shows a "No more occurrances located" message if the search looped. I want to write a unit test for the functionality of this class, the FindNextMethod is

public TextRange FindNext(IDocumentManager documentManager, IMessageBoxService messageBoxService, 
        TextEditorControl textEditor, SearchOptions options, FindAllResultSet findAllResults = null)
{
    ...
    if (options.SearchType == SearchType.CurrentDocument)
    {
        Helpers.SelectResult(textEditor, range);
        if (persistLastSearchLooped)
        {
            string message = MessageStrings.TextEditor_NoMoreOccurrances;
            messageBoxService.DisplayMessage(textEditor.Parent, message,
                Constants.Trademark, MessageBoxButtons.OK, MessageBoxIcon.Information); <- Throws here.
            Log.Trace($"TextEditorSearchProvider.FindNext(): {message}");
            lastSearchLooped = false;
        }
    }
    ...
}

我的测试是

[TestMethod]
public void FindInCurrentForwards()
{
    // Mock the IMessageBoxService.
    int dialogShownCounter = 0;
    var mock = new Mock<IMessageBoxService>();
    mock.Setup(m => m.DisplayMessage(It.IsAny<IWin32Window>(), It.IsAny<string>(), It.IsAny<string>(), 
        It.IsAny<MessageBoxButtons>(), It.IsAny<MessageBoxIcon>(), It.IsAny<MessageBoxDefaultButton>()))
         .Returns(DialogResult.OK)
         .Callback<DialogResult>(r =>
            {
                Trace.WriteLine($"MockMessageBoxService {r.ToString()}");
                dialogShownCounter++;
            });

    // Start the forward search through the first document.
    var options = new SearchOptions()
    {
        SearchText = "SomeText",
        SearchType = SearchType.CurrentDocument,
        MatchCase = false,
        MatchWholeWord = false,
        SearchForwards = false
    };
    var searchProvider = new TextEditorSearchProvider();
    var textEditor = ((TextEditorView)documentManager.GetActiveDocument().View).TextEditor;

    TextRange range = null;
    for (int i = 0; i < occurances + 1; ++i)
        range = searchProvider.FindNext(documentManager, mock.Object, textEditor, options);

    // We expect the text to be found and the dialog to be displayed once.
    Assert.IsNotNull(range);
    Assert.AreEqual(1, dialogShownCounter);
}

但是我得到一个

System.Reflection.TargetParameterCountException参数计数不匹配.

System.Reflection.TargetParameterCountException Parameter count mismatch.

我已经看到了这个

I have seen this question and I seem to be doing as the answer suggest and supplying the optional parameter but I still get the exception, why?

我在这里看到了答案,提示我必须使用具有正确参数计数的.Result,因此我尝试了

I have seen an answer here suggesting I have to use .Result with the correct parameter count, so I tried

mock.Setup(m => m.DisplayMessage(It.IsAny<IWin32Window>(), It.IsAny<string>(), It.IsAny<string>(), 
        It.IsAny<MessageBoxButtons>(), It.IsAny<MessageBoxIcon>(), It.IsAny<MessageBoxDefaultButton>()))
    .Returns((IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon,
            MessageBoxDefaultButton defaultButton) => DialogResult.OK)
    .Callback<DialogResult>(r =>
            {
                Trace.WriteLine($"MockMessageBoxService {r.ToString()}");
                dialogShownCounter++;
            });

感谢您的时间.

推荐答案

由于您的回调注册仅使用一个参数进行注册,因此抛出TargetParameterCountException.

The TargetParameterCountException is thrown because your callback registration is only registered with one parameter.

.Callback<DialogResult>(r =>
        {
            Trace.WriteLine($"MockMessageBoxService {r.ToString()}");
            dialogShownCounter++;
        });

Callback不能接受Returns返回的值.它仍然必须匹配模拟的方法签名.

The Callback cannot accept the value returned by Returns. It still has to match the mocked method signature.

.Callback((IWin32Window a1, string a2,
    string a3, MessageBoxButtons a4, MessageBoxIcon a5,
    MessageBoxDefaultButton a6) => { dialogShownCounter++ });

这篇关于使用Moq模拟使用可选参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆