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

前端之家收集整理的这篇文章主要介绍了c# – 在Moq中为返回void的方法分配参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
this question,我发现 this answer似乎是解决问题的最好方法.

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

  1. bool SomeFunc(out ISomeObject o);

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

  1. void SomeFunc(out ISomeObject o);

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

  1. public delegate void OutAction<TOut>(out TOut outVal);
  2.  
  3. public static IReturnsThrows<TMock,TReturn> OutCallback<TMock,TReturn,TOut>(
  4. this ICallback<TMock,TReturn> mock,OutAction<TOut> action)
  5. where TMock : class
  6. {
  7. // ...
  8. }

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

解决方法

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

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

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

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

  1. static class Program
  2. {
  3. static void Main()
  4. {
  5. // test the instance method from 'TestObject',passing in a mock as 'mftbt' argument
  6. var testObj = new TestObject();
  7.  
  8. var myMock = new Mock<IMyFaceToBeTested>();
  9. IMyArgFace magicalOut = new MyClass();
  10. myMock.Setup(x => x.MyMethod(out magicalOut)).Returns(true);
  11.  
  12. testObj.TestMe(myMock.Object);
  13. }
  14. }
  15.  
  16. class TestObject
  17. {
  18. internal void TestMe(IMyFaceToBeTested mftbt)
  19. {
  20. Console.WriteLine("Now code to be tested is running. Calling the method");
  21. IMyArgFace maf; // not assigned here,out parameter
  22. bool result = mftbt.MyMethod(out maf);
  23. Console.WriteLine("Method call completed");
  24. Console.WriteLine("Return value was: " + result);
  25. if (maf == null)
  26. {
  27. Console.WriteLine("out parameter was set to null");
  28. }
  29. else
  30. {
  31. Console.WriteLine("out parameter non-null; has runtime type: " + maf.GetType());
  32. }
  33. }
  34. }
  35.  
  36. public interface IMyFaceToBeTested
  37. {
  38. bool MyMethod(out IMyArgFace maf);
  39. }
  40. public interface IMyArgFace
  41. {
  42. }
  43. class MyClass : IMyArgFace
  44. {
  45. }

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

猜你在找的C#相关文章