【问题标题】:Is it possible to pass-through parameter values in Moq?是否可以在 Moq 中传递参数值?
【发布时间】:2011-11-01 23:19:59
【问题描述】:

我需要模拟HttpResponseBase.ApplyAppPathModifier,以便模拟自动返回参数ApplyAppPathModifier

我有以下代码:

var httpResponseBase = new Mock<HttpResponseBase>();
httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(/*capture this param*/))
                .Returns(/*return it here*/);

有什么想法吗?

编辑:

在 Moq 文档 (http://code.google.com/p/moq/wiki/QuickStart) 的第一页找到了解决方案:

var httpResponseBase = new Mock<HttpResponseBase>();
httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(It.IsAny<string>)
                .Returns((string value) => value);

我突然觉得自己傻了很多,不过我猜这就是你在23:30写代码时会发生的事情

【问题讨论】:

  • 我需要抛出一个传入的Exception 参数。我使用Callback() 方法(而不是Returns())来抛出它。只是为了后代和完整性。
  • @gregsdennis 太棒了!感谢您的发布。之前没有注意到 Callback() - 也许它是最近才引入的。

标签: c# testing mocking moq


【解决方案1】:

是的,您可以回显传递给方法的参数

httpResponseBase.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>()))
                .Returns((string path) => path);

如果你愿意,你也可以捕捉它

string capturedModifier = null;

httpResponseBase.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>()))
                .Callback((string path) => capturedModifier = path);

【讨论】:

    【解决方案2】:

    使用It:

    It.Is<MyClass>(mc=>mc == myValue)
    

    在这里您可以查看期望值:您期望收到的值。 在回报方面,只要回报你需要的价值。

    var tempS = string.Empty;
    var httpResponseBase = new Mock<HttpResponseBase>();
    httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(It.Is<String>(s=>{
               tempS = s;
               return s == "value I expect";
               })))
                    .Returns(tempS);
    

    【讨论】:

    • 感谢@Aliostad。刚刚也找到了解决方案的答案(将您的标记为答案)。解决方案实际上位于 Moq 文档的第一页。突然觉得自己傻了很多,不过我猜这就是你在23:30写代码的时候会发生的事情……
    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 2018-08-04
    相关资源
    最近更新 更多