在Moq中分配/ ref参数

在Moq中分配/ ref参数

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

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

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


慕的地10843
浏览 488回答 3
3回答

慕斯王

虽然问题是关于Moq 3(可能是由于其年龄),但请允许我发布Moq 4.8的解决方案,该解决方案对by-ref参数的支持有了很大改进。public interface IGobbler{&nbsp; &nbsp; bool Gobble(ref int amount);}delegate void GobbleCallback(ref int amount);&nbsp; &nbsp; &nbsp;// needed for Callbackdelegate bool GobbleReturns(ref int amount);&nbsp; &nbsp; &nbsp; // needed for Returnsvar mock = new Mock<IGobbler>();mock.Setup(m => m.Gobble(ref It.Ref<int>.IsAny))&nbsp; // match any value passed by-ref&nbsp; &nbsp; .Callback(new GobbleCallback((ref int amount) =>&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (amount > 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine("Gobbling...");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;amount -= 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;}))&nbsp; &nbsp; .Returns(new GobbleReturns((ref int amount) => amount > 0));int a = 5;bool gobbleSomeMore = true;while (gobbleSomeMore){&nbsp; &nbsp; gobbleSomeMore = mock.Object.Gobble(ref a);}顺便说一句:It.Ref<T>.IsAny也适用于C#7 in参数(因为它们也是by-ref)。
打开App,查看更多内容
随时随地看视频慕课网APP