c# – 在Moq中为返回void的方法分配参数

this question,我发现 this answer似乎是解决问题的最好方法.

提供的代码假定被模拟的函数返回一个值:

bool SomeFunc(out ISomeObject o);

但是,我想要模拟的对象有一个out函数如下:

void SomeFunc(out ISomeObject o);

来自上述答案的相关代码片段:

public delegate void OutAction<TOut>(out TOut outVal);

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

Void不是TReturn的有效类型.因此,我相信我必须以某种方式调整此代码,以使其与返回void的方法一起使用.但是怎么样?

解决方法

也许你只需要这个:
ISomeObject so = new SomeObject(...);
yourMock.Setup(x => x.someFunc(out so));

然后,当您在测试的代码中使用yourMock.Object时,so实例将“神奇地”作为out参数出现.

它有点不直观(“out in in”),但它有效.

补充:不确定我理解这个场景.以下完整程序工作正常:

static class Program
{
  static void Main()
  {
    // test the instance method from 'TestObject',passing in a mock as 'mftbt' argument
    var testObj = new TestObject();

    var myMock = new Mock<IMyFacetoBeTested>();
    IMyArgFace magicalOut = new MyClass();
    myMock.Setup(x => x.MyMethod(out magicalOut)).Returns(true);

    testObj.TestMe(myMock.Object);
  }
}

class TestObject
{
  internal void TestMe(IMyFacetoBeTested mftbt)
  {
    Console.WriteLine("Now code to be tested is running. Calling the method");
    IMyArgFace maf; // not assigned here,out parameter
    bool result = mftbt.MyMethod(out maf);
    Console.WriteLine("Method call completed");
    Console.WriteLine("Return value was: " + result);
    if (maf == null)
    {
      Console.WriteLine("out parameter was set to null");
    }
    else
    {
      Console.WriteLine("out parameter non-null; has runtime type: " + maf.GetType());
    }
  }
}

public interface IMyFacetoBeTested
{
  bool MyMethod(out IMyArgFace maf);
}
public interface IMyArgFace
{
}
class MyClass : IMyArgFace
{
}

请通过使用我的示例中的类和接口的名称来说明您的情况有何不同.

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么