【问题标题】:How do I mock a Dialog service method which displays a prompt using nunit and moq如何模拟使用 nunit 和 moq 显示提示的 Dialog 服务方法
【发布时间】:2021-07-31 12:20:00
【问题描述】:

我有一个对话服务被用作:

this.dialogService.ShowConfirm(
    async (dialogRes, error) =>
    {
        if (dialogRes == true)
        {
            await Action(win);
        }
    },
    "Prompt message");

我试图设置一个回调并模拟它的执行方式:

this.mockDialogService
    .Setup(x => x.ShowConfirm(
        It.IsAny<Action<bool, Exception>>(), 
        It.IsAny<string>(), 
        It.IsAny<string>(), 
        It.IsAny<string>(), 
        It.IsAny<ContentControl>(), 
        It.IsAny<string>()))
    .Callback((Action<bool, Exception> action) => 
        action.Invoke(true, new Exception()));

但是不起作用,抛出异常:

System.ArgumentException : 无效回调。设置带参数的方法(Action&lt;bool, Exception&gt;, string, string, string, ContentControl, string) 无法调用带参数的回调(Action&lt;bool, Exception&gt;)

我被它困住了,因为我不知道如何继续嘲笑它。

【问题讨论】:

  • 正如错误信息所说:你在回调中给出的方法没有足够的参数。并不是说即使ShowConfirm 具有参数的默认值,您仍然需要列出该参数。
  • @KlausGütter 那么在这种情况下,Action&lt;bool,Exception&gt; 会发生什么,因为我需要提供一个值对吗?
  • @KlausGütter 我希望通过设置 dialogRes 值来实现默认功能,我该怎么做
  • 方法签名似乎是(Action&lt;bool, Exception&gt;, string, string, string, ContentControl, string)(即6个参数),但您的回调只有一个参数(Action&lt;bool, Exception&gt; action)。只需将其他 5 个参数添加到您的回调中。
  • 只需将Callback((Action&lt;bool, Exception&gt; action) =&gt; 更改为Callback((Action&lt;bool, Exception&gt; action, string p2, string p3, string p4, ContentControl p5, string p6) =&gt;

标签: c# unit-testing nunit moq


【解决方案1】:

正如错误消息所说:您在回调中提供的方法没有足够的参数。请注意,即使 ShowConfirm 具有参数的默认值,您仍然需要列出参数:

this.mockDialogService
    .Setup(x => x.ShowConfirm(
        It.IsAny<Action<bool, Exception>>(), 
        It.IsAny<string>(), 
        It.IsAny<string>(), 
        It.IsAny<string>(), 
        It.IsAny<ContentControl>(), 
        It.IsAny<string>()))
    .Callback((Action<bool, Exception> action, string p2, string p3, string p4, ContentControl p5, string p6) => 
        action.Invoke(true, new Exception()));

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    相关资源
    最近更新 更多