使用Moq&NUnit作为一个存储库(遵循本教程),我遇到了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.
发现有一些错误的DLL引用。完全删除Moq并通过Nuget重新安装解决了这个问题。
对我来说,在将Moq版本4.0.10827更新到4.10.1之后,问题已经消失。
我是在尝试相同的教程后才发现这一点的,在教程中我也遇到了相同的TypeInitializationException
和ArgumentException
。
在看到其他一些答案后,我发现我安装了v4.0.10827。
我更新到了最新版本(在撰写本文时是v4.16.0.0)。更新后,我不再看到异常。