c# - 为需要 Func 并返回 IEnumerable 的 protected 虚拟方法设置 Moq 调用

标签 c# unit-testing moq

我有以下代码。

public class MyClass
{
    protected virtual IEnumerable<TResult> MyMethod<TResult>(Func<IDataReader, IEnumerable<TResult>> arg)
    {
       ....
    }
} 

如何为此设置模拟方法?

我尝试遵循但收到错误。

using Moq;
using Moq.Protected;
namespace Foo
{
    [TestClass]
    public class TestClass
    {
        Mock<MyClass> m_mockObject = null;
        [TestMethod]
        public void MyTest()
        {
            m_mockObject = new Mock<MyClass>();
            AddMethod<Func<IDataReader, IEnumerable<SomeOtherClass>>, IEnumerable<SomeOtherClass>>(this.MyMethod);

        }

        private void AddMethod<TIn, TResult>(Func<TIn, TResult> method)
        {
             m_mockObject.Protected().Setup<TResult>(method.Method.Name, ItExpr.IsAny<TIn>())
                                                    .Returns(method); /* THIS LINE IS THROWING THE EXCEPTION */
        }

        public IEnumerable<TResult> MyMethod<TResult>(Func<IDataReader, IEnumerable<TResult>> arg)
        {
            ....
        }
    }
}

运行代码后,在调用设置函数时出现以下错误。

> System.ArgumentException was unhandled by user code
  HResult=-2147024809
  Message=Expression of type 'System.Object' cannot be used for return type 'System.Collections.Generic.IEnumerable`1[SomeOtherClass]'
  Source=System.Core
  StackTrace:
       at System.Linq.Expressions.Expression.ValidateLambdaArgs(Type delegateType, Expression& body, ReadOnlyCollection`1 parameters)
       at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, String name, Boolean tailCall, IEnumerable`1 parameters)
       at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, Boolean tailCall, IEnumerable`1 parameters)
       at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, ParameterExpression[] parameters)
       at Moq.Protected.ProtectedMock`1.Setup[TResult](String methodOrPropertyName, Object[] args)
       ....
       .....
  InnerException: 

最佳答案

不确定为什么你要返回一个方法..但你可以尝试将其更改为:

m_mockObject.Protected().Setup<IEnumerable<TResult>>(method.Method.Name, ItExpr.IsAny<TIn>()).Returns(new List<TResult>());

看看是否有效..

关于c# - 为需要 Func 并返回 IEnumerable 的 protected 虚拟方法设置 Moq 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791055/

相关文章:

python - 成功单元测试pyinotify?

F# 起订量返回 "Invalid setup on a static member"

c# - 模拟 OpenXML SDK SpreadsheetDocument

c# - Moq - 检查具体类的方法调用

c# - 使用 ToString() 获得与 String.Format 相同的结果

c# - Entity Framework 不导入具有 super 键的表

c# - 读取外部配置文件

c++ - 使用 Google C++ Mocking Framework (Google Mock) (V1.5) 将任意参数传递给调用的方法

.net - 发送电子邮件并创建新线程的单元测试

c# - 如何使用最小起订量模拟 Entity Framework DbRawSqlQuery 对象?