在Moq中分配/ ref参数

Ric*_*lay 268 c# parameters moq ref out

是否可以使用Moq(3.0+)分配out/ ref参数?

我看过使用Callback(),但Action<>不支持ref参数,因为它基于泛型.我也最好It.Isref参数的输入上放置一个约束(),尽管我可以在回调中做到这一点.

我知道Rhino Mocks支持这个功能,但我正在研究的项目已经在使用Moq了.

Cra*_*ste 300

对于'out',以下似乎对我有用.

public interface IService
{
    void DoSomething(out string a);
}

[TestMethod]
public void Test()
{
    var service = new Mock<IService>();
    var expectedValue = "value";
    service.Setup(s => s.DoSomething(out expectedValue));

    string actualValue;
    service.Object.DoSomething(out actualValue);
    Assert.AreEqual(expectedValue, actualValue);
}
Run Code Online (Sandbox Code Playgroud)

我猜测当你调用安装程序并记住它时,Moq会查看'expectedValue'的值.

因为ref,我也在寻找答案.

我发现以下QuickStart指南很有用:https: //github.com/Moq/moq4/wiki/Quickstart

  • 当Mocked接口方法在具有其自己的引用输出变量的不同作用域中执行时(例如在另一个类的方法内部),这对我不起作用.上面给出的示例很方便,因为执行发生在与模拟设置,但是解决所有场景太简单了.支持显式处理out/ref值在moq中很弱(正如其他人所说,在执行时处理). (9认同)
  • 我认为我遇到的问题是,没有方法_assigning_ out/ref params来自方法`Setup` (6认同)
  • @azeglov 不,它适用于任何类型的“out”参数。您确定您的“Setup”匹配正确吗?否则,如果您有一个松散的模拟,当没有“Setup”相关时,它可能只使用默认行为。如果您想确保 Moq 不会因为确定没有“Setup”匹配而回退到空实现,请使用“MockBehavior.Strict”。 (3认同)
  • +1:这是一个有用的答案.但是:如果out参数类型是一个类而不是像string这样的内置类型 - 我不相信这会起作用.今天试了一下.模拟对象模拟调用并通过"out"参数返回null. (2认同)

sta*_*ica 94

虽然问题是关于Moq 3(可能是由于其年龄),但请允许我发布Moq 4.8的解决方案,该解决方案对by-ref参数的支持有了很大改进.

public interface IGobbler
{
    bool Gobble(ref int amount);
}

delegate void GobbleCallback(ref int amount);     // needed for Callback
delegate bool GobbleReturns(ref int amount);      // needed for Returns

var mock = new Mock<IGobbler>();
mock.Setup(m => m.Gobble(ref It.Ref<int>.IsAny))  // match any value passed by-ref
    .Callback(new GobbleCallback((ref int amount) =>
     {
         if (amount > 0)
         {
             Console.WriteLine("Gobbling...");
             amount -= 1;
         }
     }))
    .Returns(new GobbleReturns((ref int amount) => amount > 0));

int a = 5;
bool gobbleSomeMore = true;
while (gobbleSomeMore)
{
    gobbleSomeMore = mock.Object.Gobble(ref a);
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句:out也适用于C#7 It.Ref<T>.IsAny参数(因为它们也是by-ref).

  • 值得一提的是,如果您模拟的函数有更多参数,则回调签名应遵循相同的模式(而不仅仅是 ref/out 参数) (3认同)
  • 这是解决方案,它使您可以将任何输入都用作参考,就像在非参考输入中一样。确实,这是一个非常不错的改进支持 (2认同)
  • 但是,相同的解决方案不适用于`out`,是吗? (2认同)
  • @ATD 部分是的。使用 out 参数声明委托,并使用上面的语法在回调中分配值 (2认同)

Sco*_*ner 84

编辑:在Moq 4.10中,您现在可以将具有out或ref参数的委托直接传递给Callback函数:

mock
  .Setup(x=>x.Method(out d))
  .Callback(myDelegate)
  .Returns(...); 
Run Code Online (Sandbox Code Playgroud)

您将必须定义委托并实例化它:

...
.Callback(new MyDelegate((out decimal v)=>v=12m))
...
Run Code Online (Sandbox Code Playgroud)

对于4.10之前的Moq版本:

Avner Kashtan在他的博客中提供了一种扩展方法,允许从回调中设置out参数:Moq,Callbacks和Out参数:一个特别棘手的边缘情况

解决方案既优雅又hacky.优雅的是它提供了一种流畅的语法,让人感觉与其他Moq回调在家.而hacky因为它依赖于通过反射调用一些内部Moq API.

上面链接提供的扩展方法没有为我编译,所以我在下面提供了一个编辑版本.您需要为每个输入参数创建一个签名; 我提供了0和1,但进一步扩展应该很简单:

public static class MoqExtensions
{
    public delegate void OutAction<TOut>(out TOut outVal);
    public delegate void OutAction<in T1,TOut>(T1 arg1, out TOut outVal);

    public static IReturnsThrows<TMock, TReturn> OutCallback<TMock, TReturn, TOut>(this ICallback<TMock, TReturn> mock, OutAction<TOut> action)
        where TMock : class
    {
        return OutCallbackInternal(mock, action);
    }

    public static IReturnsThrows<TMock, TReturn> OutCallback<TMock, TReturn, T1, TOut>(this ICallback<TMock, TReturn> mock, OutAction<T1, TOut> action)
        where TMock : class
    {
        return OutCallbackInternal(mock, action);
    }

    private static IReturnsThrows<TMock, TReturn> OutCallbackInternal<TMock, TReturn>(ICallback<TMock, TReturn> mock, object action)
        where TMock : class
    {
        mock.GetType()
            .Assembly.GetType("Moq.MethodCall")
            .InvokeMember("SetCallbackWithArguments", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock,
                new[] { action });
        return mock as IReturnsThrows<TMock, TReturn>;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用上面的扩展方法,您可以使用out参数测试接口,例如:

public interface IParser
{
    bool TryParse(string token, out int value);
}
Run Code Online (Sandbox Code Playgroud)

..使用以下Moq设置:

    [TestMethod]
    public void ParserTest()
    {
        Mock<IParser> parserMock = new Mock<IParser>();

        int outVal;
        parserMock
            .Setup(p => p.TryParse("6", out outVal))
            .OutCallback((string t, out int v) => v = 6)
            .Returns(true);

        int actualValue;
        bool ret = parserMock.Object.TryParse("6", out actualValue);

        Assert.IsTrue(ret);
        Assert.AreEqual(6, actualValue);
    }
Run Code Online (Sandbox Code Playgroud)



编辑:要支持void-return方法,您只需添加新的重载方法:

public static ICallbackResult OutCallback<TOut>(this ICallback mock, OutAction<TOut> action)
{
    return OutCallbackInternal(mock, action);
}

public static ICallbackResult OutCallback<T1, TOut>(this ICallback mock, OutAction<T1, TOut> action)
{
    return OutCallbackInternal(mock, action);
}

private static ICallbackResult OutCallbackInternal(ICallback mock, object action)
{
    mock.GetType().Assembly.GetType("Moq.MethodCall")
        .InvokeMember("SetCallbackWithArguments", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock, new[] { action });
    return (ICallbackResult)mock;
}
Run Code Online (Sandbox Code Playgroud)

这允许测试接口,例如:

public interface IValidationRule
{
    void Validate(string input, out string message);
}

[TestMethod]
public void ValidatorTest()
{
    Mock<IValidationRule> validatorMock = new Mock<IValidationRule>();

    string outMessage;
    validatorMock
        .Setup(v => v.Validate("input", out outMessage))
        .OutCallback((string i, out string m) => m  = "success");

    string actualMessage;
    validatorMock.Object.Validate("input", out actualMessage);

    Assert.AreEqual("success", actualMessage);
}
Run Code Online (Sandbox Code Playgroud)

  • @Wilbert,我已经用void-return函数的额外重载更新了我的答案. (5认同)
  • 我一直在我们的测试套件中使用此解决方案,并且一直在工作。但是,由于更新到Moq 4.10,因此不再有效。 (2认同)
  • 它似乎在此提交中被破坏了https://github.com/moq/moq4/commit/a605c281b812ab83d829e40018c37f00b6de52c6.也许现在有更好的方法吗? (2认同)
  • 仅供参考 Moq4 中的 MethodCall 现在是设置的属性,因此上面的 OutCallbackInternal 的内容更改为 `var methodCall = mock.GetType().GetProperty("Setup").GetValue(mock); mock.GetType().Assembly.GetType("Moq.MethodCall") .InvokeMember("SetCallbackResponse", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, methodCall, new[] { action });` (2认同)

Kos*_*sau 48

这是Moq网站的文档:

// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);


// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);
Run Code Online (Sandbox Code Playgroud)

  • 这与Parched的答案基本相同,并且具有相同的限制,因为它不能根据输入更改输出值,也不能响应ref参数. (5认同)

Gis*_*shu 17

似乎不可能开箱即用.看起来有人尝试解决方案

请参阅此论坛帖子 http://code.google.com/p/moq/issues/detail?id=176

此问题 用Moq验证参考参数的值


Mar*_*ijn 15

在 Billy Jakes awnser 的基础上,我创建了一个带有 out 参数的完全动态的模拟方法。我把这个贴在这里给任何觉得有用的人。

// Define a delegate with the params of the method that returns void.
delegate void methodDelegate(int x, out string output);

// Define a variable to store the return value.
bool returnValue;

// Mock the method: 
// Do all logic in .Callback and store the return value.
// Then return the return value in the .Returns
mockHighlighter.Setup(h => h.SomeMethod(It.IsAny<int>(), out It.Ref<int>.IsAny))
  .Callback(new methodDelegate((int x, out int output) =>
  {
    // do some logic to set the output and return value.
    output = ...
    returnValue = ...
  }))
  .Returns(() => returnValue);
Run Code Online (Sandbox Code Playgroud)


Red*_*ood 14

在 VS2022 中你可以简单地执行以下操作:

foo.Setup(e => e.TryGetValue(out It.Ref<ExampleType>.IsAny))
    .Returns((ref ExampleType exampleType) => {
        exampleType = new ExampleType();
        return true;
})
Run Code Online (Sandbox Code Playgroud)