为了账号安全,请及时绑定邮箱和手机立即绑定

在Moq中分配/ ref参数

在Moq中分配/ ref参数

C#
慕的地10843 2019-07-30 15:21:12
在Moq中分配/ ref参数是否可以使用Moq(3.0+)分配out/ ref参数?我看过使用Callback(),但Action<>不支持ref参数,因为它基于泛型。我也最好It.Is在ref参数的输入上放置一个约束(),尽管我可以在回调中做到这一点。我知道Rhino Mocks支持这个功能,但我正在研究的项目已经在使用Moq了。
查看完整描述

3 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

虽然问题是关于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);

}

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


查看完整回答
反对 回复 2019-07-30
  • 3 回答
  • 0 关注
  • 487 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信