模拟应用程序用户并提供角色



我试图为我嘲笑的ApplicationUserManager提供一个ApplicationUser。 当我尝试添加角色时,我注意到Roles是只读属性。 不确定在我的测试中实现的最佳方式。

[TestMethod]
public void AccountPerission_PermissionScope()
{
    //Arrange
    IRolePermissionSvc roleService = GetRoleService();
    IUserPermissionSvc userService = GetUserService();
    AccountController controller = new AccountController(
        _applicationUserManager.Object, 
        null,
        _staffTypeSvc.Object,
        _militaryBaseSvc.Object,
        _positionTitleSvc.Object,
        userService,
        roleService
        );
    var appUser = new ApplicationUser()
    {
        FirstName = "test",
        LastName = "tester",
        Id = "02dfeb89-9b80-4884-b694-862adf38f09d",
        Roles = new List<ApplicationRoles> { new ApplicationRole { Id = "1" } } // This doesn't work.
    };
    //Act
    _applicationUserManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult<ApplicationUser>(appUser));
    Task<PartialViewResult> result = controller.AjaxResetUserPermission(appUser.Id, 1);
    //Assert
    Assert.IsNotNull(result);
}

虽然角色是只读属性,但它是virtual的,这意味着它可以在派生类中重写。因此,您可以创建一个派生自ApplicationUser

public class MockApplicationUser : ApplicationUser {
    private readonly ICollection<ApplicationRoles> roles
    public MockedApplicationUser(List<ApplicationRoles> roles) : base() {
        this.roles = roles;
    }
    public override ICollection<ApplicationRoles> Roles {
        get { return roles; }
    }
}

并在测试中使用它

var appUser = new MockApplicationUser(new List<ApplicationRoles> { new ApplicationRole { Id = "1" } })
{
    FirstName = "test",
    LastName = "tester",
    Id = "02dfeb89-9b80-4884-b694-862adf38f09d"
};

或模拟ApplicationUser并设置 Roles 属性

var roles = new List<ApplicationRoles> { new ApplicationRole { Id = "1" } };
var appUserMock = new Mock<ApplicationUser>();
appUserMock.SetupAllProperties();
appUserMock.Setup(m => m.Roles).Returns(roles);
var appUser = appUserMock.Object;    
appUser.FirstName = "test";
appUser.LastName = "tester";
appUser.Id = "02dfeb89-9b80-4884-b694-862adf38f09d";

顺便说一句,测试方法也可以异步

[TestMethod]
public async Task AccountPerission_PermissionScope() {
    //Arrange
    //..code removed for brevity
    _applicationUserManager
        .Setup(x => x.FindByIdAsync(It.IsAny<string>()))
        .ReturnsAsync(appUser);
    //Act    
    var result = await controller.AjaxResetUserPermission(appUser.Id, 1);
    //Assert
    Assert.IsNotNull(result);
}

相关内容

  • 没有找到相关文章

最新更新