3

I am trying to supply an ApplicationUser to my mocked ApplicationUserManager. When I try and add roles I notice that Roles is a read-only property. Not sure the best way to implement in my test.

[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);
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
CBC_NS
  • 1,961
  • 4
  • 27
  • 47

1 Answers1

3

While Roles is a read-only property, it is virtual which means that it can be overridden in a derived class. So you can either create a class derived from 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; }
    }
}

and use that in the test

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

or mock the ApplicationUser and setup the Roles property

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";

As an aside, the test method can also be made async

[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);
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472