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

我已经看过使用Callback(),但Action<>不支持ref参数,因为它是基于泛型的。我还希望在ref参数的输入上放置一个约束(It.Is),尽管我可以在回调中这样做。

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


当前回答

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的参数(因为它们也是by-ref)。

其他回答

似乎不可能开箱即用。看来有人想要解决问题

请看这个论坛帖子 http://code.google.com/p/moq/issues/detail?id=176

这个问题 用最小订货量验证参考参数的值

今天下午,我为此纠结了一个小时,但在任何地方都找不到答案。在我自己玩了一圈之后,我能够想出一个适合我的解决方案。

string firstOutParam = "first out parameter string";
string secondOutParam = 100;
mock.SetupAllProperties();
mock.Setup(m=>m.Method(out firstOutParam, out secondOutParam)).Returns(value);

这里的关键是mock.SetupAllProperties();这将为您清除所有属性。这可能并不适用于每个测试用例场景,但如果您所关心的只是获取YourMethod的返回值,那么这将很好地工作。

下面是一个正在工作的例子。

[Fact]
public void DeclineLowIncomeApplicationsOutDemo()
{
    var mockValidator = new Mock<IFrequentFlyerNumberValidator>();

    var isValid = true; // Whatever we set here, thats what we will get.

    mockValidator.Setup(x => x.IsValid(It.IsAny<string>(), out isValid));

    var sut = new CreditCardApplicationEvaluator(mockValidator.Object);

    var application = new CreditCardApplication
    {
        GrossAnnualIncome = 19_999,
        Age = 42
    };

    var decision = sut.EvaluateUsingOut(application);

    Assert.Equal(CreditCardApplicationDecision.AutoDeclined, decision);
}

public interface IFrequentFlyerNumberValidator
{
    bool IsValid(string frequentFlyerNumber);
    void IsValid(string frequentFlyerNumber, out bool isValid);
}

注意,在设置中没有return,因为没有return。

在VS2022中,你可以简单地做:

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

在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);