我正在尝试使用 Moq 创建一个单元测试来测试 MongoDB.AspNet.Identity V2提供者。这句话让我很伤心:
var appUser = new Mock<PreRegistrationMVC.Models.ApplicationUser>();
var userStore = new Mock<MongoDB.AspNet.Identity.UserStore<PreRegistrationMVC.Models.ApplicationUser>>();
似乎 userStore 无法正确实例化,这是错误。
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException was unhandled by user code
HResult=-2147024809
Message=Can not instantiate proxy of class: MongoDB.AspNet.Identity.UserStore`1[[MVC.Models.ApplicationUser, MVC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
Could not find a parameterless constructor.
Source=Moq
StackTrace:
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance(Type proxyType, List`1 proxyArguments, Type classToProxy, Object[] constructorArguments)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at Moq.Proxy.CastleProxyFactory.CreateProxy(Type mockType, ICallInterceptor interceptor, Type[] interfaces, Object[] arguments)
at Moq.Mock`1.<InitializeInstance>b__2()
at Moq.PexProtector.Invoke(Action action)
at Moq.Mock`1.InitializeInstance()
at Moq.Mock`1.OnGetObject()
at Moq.Mock.GetObject()
at Moq.Mock.get_Object()
at Moq.Mock`1.get_Object()
at MVC_Tests.Identity.Accounts.AccountController_Test.TestSuccessfulRegister() in c:\Users\Tim\Documents\Visual Studio 2013\Projects\PreRegistrationApp\MVC_Tests\Identity\Accounts\AccountController_Test.cs:line 108
InnerException:
我对 Moq 完全陌生,所以我正在寻找: Moq 需要什么类型的设置来实例化它? UserStore 类是否存在与 Moq 不兼容的问题?
感谢阅读。
最佳答案
MOQ 适用于模拟接口(interface),但不适用于具体类。所以不要模拟具体的类,而是要求接口(interface):
var userStore = new Mock<IUserStore<PreRegistrationMVC.Models.ApplicationUser>>();
另外 ApplicationUser
应该是 POCO,所以不需要模拟它,只需创建它的实例,没有 MOQ 并在测试中使用。
关于mongodb - 无法实例化代理...找不到无参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25649155/