尝试模拟实体框架上下文时抛出TargetInvocationException

时间:2015-03-20 16:01:39

标签: c# entity-framework moq

使用Moq& amp;编写单元测试时对于存储库的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.

3 个答案:

答案 0 :(得分:4)

原来有一些错误的DLL引用。完全删除Moq并通过Nuget重新安装修复了问题。

答案 1 :(得分:0)

Foos是一种财产;使用mockedContext.SetupGet(c=>c.Foos).Return…

答案 2 :(得分:0)

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

相关问题