无法实例化代理...无法找到无参数构造函数

Chi*_*ago 23 moq mongodb asp.net-identity

我正在尝试使用Moq创建一个单元测试,测试MongoDB.AspNet.Identity V2提供程序.这条线给了我悲伤:

var appUser = new Mock<PreRegistrationMVC.Models.ApplicationUser>();
var userStore = new Mock<MongoDB.AspNet.Identity.UserStore<PreRegistrationMVC.Models.ApplicationUser>>();
Run Code Online (Sandbox Code Playgroud)

似乎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: 
Run Code Online (Sandbox Code Playgroud)

我是Moq的新手所以我正在寻找:Moq需要什么类型的设置才能实例化?有没有关于UserStore类的东西不能很好地与Moq一起使用?

谢谢阅读.

tra*_*max 30

MOQ适用于模拟接口,但在具体类中效果不佳.因此,不要嘲笑具体的类,而是要求接口:

var userStore = new Mock<IUserStore<PreRegistrationMVC.Models.ApplicationUser>>();
Run Code Online (Sandbox Code Playgroud)

ApplicationUser应该是POCO,所以不需要模拟它,只需创建没有MOQ的实例并在测试中使用.


Rem*_*tec 8

我有这个问题。我写过...

var x = new Mock<Concrete>();
Run Code Online (Sandbox Code Playgroud)

... 代替 ...

var x = new Mock<IConcrete>();
Run Code Online (Sandbox Code Playgroud)


Ash*_*lam 6

您可以尝试引用模拟行为,如下所示

Mock<testClass>(MockBehavior.Strict, new object[] {"Hello"}); 
Run Code Online (Sandbox Code Playgroud)

  • 由于它是params参数,因此可以写为“ new Mock &lt;testClass&gt;(MockBehavior.Strict,“ Hello”);“ (4认同)

mer*_*zda 6

我知道这是一个迟到的响应,但我一直在寻找答案并且找不到我需要的确切答案,但是在创建模拟时,您可以将参数传递给您想要的构造函数。

例如,如果您有这样的课程:

public class Foo
{
    private readonly Boo _boo;

    public Foo(Boo boo)
    {
        _boo = boo;
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样模拟它:

private readonly Mock<Foo> _foo = new Mock<Foo>(new Mock<Boo>().Object);
Run Code Online (Sandbox Code Playgroud)