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

标签 c# .net generics moq

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 is 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
{
}

请使用我的示例中的类名和接口(interface),说明您的情况有何不同。

关于c# - 在 Moq 中为返回 void 的方法分配参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20046963/

相关文章:

c# - ASP :menu error occuring

c# - 远程方法调用的 .NET 标准是什么?

java - 类型参数 E 隐藏了类型 E。尝试了不同的变体,但仍然无法修复

c# - 枚举从表单发送的所有值

c# - 在命令提示符 (cmd) 中执行 C#

c# - SqlDataReader 执行错误

C# : overriding Method with optional parameters & named parameters : Unexpected Result

c# - 为什么 GridView 没有显示在浏览器上?

Java 泛型类型删除 : when and what happens?

java - 是否可以同时对有界泛型类和泛型接口(interface)进行泛型子类化?