测试具有空的IdentityResult

时间:2019-02-14 12:54:26

标签: c# asp.net-mvc moq

我有方法

  public async Task<ActionResult> CreateRole(RoleModel roleViewModel)
    {
        if (ModelState.IsValid)
        {
            RoleModel role = new RoleModel(roleViewModel.Name);

            // Save the new Description property:
            role.Description = roleViewModel.Description; // <--- Here you have assign the Description value

            IdentityResult roleResult = await roleManager.CreateRoleAsync(role);

            if (roleResult.Succeeded)
            {
                return RedirectToAction("Index");
            }
            else
            {
                AddErrorsFromResult(roleResult);
            }
        }
        return View(roleViewModel);
    }

创建角色,它可以正常工作,但是当我要进行模拟测试时,我具有空IdentityResult。我不明白是什么问题。

我的测试

public async Task CanCreateRoleAsync()
    {
        //arrange
        Task<IdentityResult> successResult = Task.FromResult(IdentityResult.Success);
        Mock<IRoleManagerRepository> mockRole = new Mock<IRoleManagerRepository>();
        Mock<IUserManagerRepository> mockUser = new Mock<IUserManagerRepository>();
        RoleController controller = new RoleController(mockRole.Object, mockUser.Object);

        RoleModel model = new RoleModel { Id = "test-test-test-test", Name = "test", Description = "test user" };

        mockRole.Setup(m => m.CreateRoleAsync(model)).Returns(successResult);

        //action
        ActionResult result = await controller.CreateRole(model);

        //assert
        Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
    }

以及创建角色的方法

public async Task<IdentityResult> CreateRoleAsync(RoleModel applicationRole)
    {
        IdentityResult result = await userRole.CreateAsync(applicationRole);
        return result;
    }

此时为空

enter image description here

和称为NullReferenceException object reference does not indicate an object instance.的错误

1 个答案:

答案 0 :(得分:1)

猜猜是因为输入不匹配。您的设置使用一个RoleModel实例,然后实际的方法调用使用在CreateRole内部创建的另一实例。

对其进行设置,使其可以容纳任何物体:

mockRole.Setup(m => m.CreateRoleAsync(It.IsAny<RoleModel>()))
        .Returns(successResult);