【问题标题】:TargetInvocationException thrown when trying to mock Entity Framework context尝试模拟实体框架上下文时抛出 TargetInvocationException
【发布时间】:2015-05-24 02:53:38
【问题描述】:

在使用 Moq 和 NUnit 为存储库编写单元测试时(遵循 this tutorial),我遇到了 TargetInvocationException,我不知道为什么会抛出它。

var fooList = new List<Foo>
{
    new Foo() { Id = 1, Name = "Something" },
    new Foo() { Id = 2, Name = "Some other thing" }
}.AsQueryable();

var mockedFooSet = new Mock<DbSet<Foo>>(fooList);
mockedFooSet.As<IQueryable<Foo>>().Setup(m => m.Provider).Returns(fooList.Provider);
mockedFooSet.As<IQueryable<Foo>>().Setup(m => m.Expression).Returns(fooList.Expression);
mockedFooSet.As<IQueryable<Foo>>().Setup(m => m.ElementType).Returns(fooList.ElementType);
mockedFooSet.As<IQueryable<Foo>>().Setup(m => m.GetEnumerator()).Returns(fooList.GetEnumerator()); 

var mockedContext = new Mock<FooContext>();
mockedContext.Setup(context => context.Foos).Returns(mockedFooSet.Object);

TargetInvocationException 在最后一行被抛出。我在这里错过了什么明显的东西吗?我将如何解决这个问题?如果有人能解释一下我在这里做错了什么,我将不胜感激。

编辑:错误信息

System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
----> System.TypeInitializationException : The type initializer for 'Castle.Proxies.DbSet`1Proxy' threw an exception.
----> System.ArgumentException : Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

【问题讨论】:

    标签: c# entity-framework moq


    【解决方案1】:

    原来有一些错误的 DLL 引用。完全删除起订量并通过 Nuget 重新安装解决了问题。

    【讨论】:

    • 不敢相信。我先浪费了一个小时尝试其他解决方案,但这是正确的:)
    【解决方案2】:

    Foos 是一个属性;使用mockedContext.SetupGet(c=&gt;c.Foos).Return…

    【讨论】:

    • 感谢您的回复!但是,将 Setup 更改为 SetupGet 并不能解决问题。我在问题中添加了异常消息。
    【解决方案3】:

    对我来说,在将 Moq 版本 4.0.10827 更新到 4.10.1 后,问题就消失了。

    【讨论】:

      【解决方案4】:

      我只是在尝试相同的教程后遇到了这个问题,在其中我也遇到了相同的 TypeInitializationExceptionArgumentException

      在看到其他一些答案后,我发现我安装了 v4.0.10827。

      我已更新到最新版本(在撰写本文时为 v4.16.0.0)。更新后我不再看到异常。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-07
        • 2016-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多