Moq表示无法为接口模拟传递Constructor参数

时间:2017-09-06 03:59:47

标签: asp.net-mvc unit-testing authentication moq

我的应用程序ASP.NET MVC 5的测试有点像这样

  

Castle.Proxies.IdentityUserLogin :: EntityType'IdentityUserLogin'没有定义键。定义此EntityType的键。   Castle.Proxies.IdentityUserRole :: EntityType'IdentityUserRole'没有定义键。定义此EntityType的键。   IdentityUserLogins:EntityType:EntitySet'IdentityUserLogins'基于没有定义键的类型'IdentityUserLogin'。   IdentityUserRoles:EntityType:EntitySet'IdentityUserRoles'基于类型'IdentityUserRole',没有定义键。

我测试了UserService,我使用的是Moq和NUnit框架。当我添加这个时,我解决了所有问题:

var mockContext = new Mock<SomeContext>() { CallBase = true };

但现在我遇到了这个问题:

  

消息:System.ArgumentException:无法为接口模拟传递构造函数参数。

如果你想要,你可以查看下面我的代码,但我认为仅在“mockContext”中有问题

[Test, TestCaseSource(typeof(UserServiceTestData), nameof(UserServiceTestData.WrongCreateUserTestCases))]
    public void ShouldWrongUserCreationTest(UserDTO userDto)
    {
        //Arrange
        var user = new ApplicationUser
        {
            Email = "test",
            Roles = { new IdentityUserRole { UserId = "test", RoleId = "test" } },
            ClientProfile = new ClientProfile { Name = "test" }
        };

        var mockStore = new Mock<IUserStore<ApplicationUser>>();
        mockStore.Setup(x => x.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(user));
        mockStore.As<IUserEmailStore<ApplicationUser>>().Setup(x => x.FindByEmailAsync("existed")).Returns(Task.FromResult((ApplicationUser)null));
        mockStore.As<IUserPasswordStore<ApplicationUser>>();
        mockStore.As<IUserRoleStore<ApplicationUser>>().Setup(x => x.AddToRoleAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
            .Returns(Task.FromResult(IdentityResult.Success));
        mockStore.As<IUserRoleStore<ApplicationUser>>().Setup(x => x.GetRolesAsync(It.IsAny<ApplicationUser>()))
           .Returns(Task.FromResult((IList<string>)new List<string>()));
        mockStore.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>()))
            .Returns(Task.FromResult(IdentityResult.Success));

        var mockDbSet = new Mock<DbSet<ClientProfile>>(MockBehavior.Strict);
        mockDbSet.Setup(x => x.Add(It.IsAny<ClientProfile>())).Returns(new ClientProfile());

        var userManager = new ApplicationUserManager(mockStore.Object);
        var mockContext = new Mock<AuthenticationContext>() { CallBase = true };
        var mock = new Mock<IIdentityUnitOfWork>(mockContext.Object);
        mock.Setup(a => a.UserManager).Returns(userManager);

        //Act
        var userService = new UserService(mock.Object);
        OperationDetails result = userService.Create(userDto);

        //Assert
        Assert.That(result.Succedeed, Is.False);
    }

1 个答案:

答案 0 :(得分:1)

我猜问题就在这一行:

var mock = new Mock<IIdentityUnitOfWork>(mockContext.Object);

moq基于IIdentityUnitOfWork创建的动态类只有默认构造函数,它不知道如何处理mockContext.Object。 从模拟构造函数中删除mockContext.Object应该可以解决您的问题。