I have the following code:
var clientId = this.UserManager.FindById(this.User.Identity.GetUserId()).ClientId;
and this is part of one of the controllers of my application. Now I am writing block tests and have to go through this thing to check the actual properties of the controller.
The problem is that it throws a null reference exception because it UserManager.FindByIdreturns null. If I can mock this, then it has the ClientId property, I can avoid the exception.
What have i tried? First mocks UserManager itself:
var fakeUserManager = new Mock<ApplicationUserManager>();
fakeUserManager.Setup(x => x.FindById(It.IsAny<string>()))
.Returns(user);
But when I try to install my .UserManager controller for it:
controller.UserManager = fakeUserManager.Object;
Visual Studio says that the UserManager cannot be used in this context because the access set is not available.
I decided to create the user using the UserManager, but the create method again throws a null reference.
ApplicationUserManager:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
:
@mason . , , .
-, @mason, UserManager .
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
set
{
_userManager = value;
}
}
-, . ApplicationUserManager , IUserStore:
var store = new Mock<IUserStore<User>>(MockBehavior.Strict);
store.As<IUserStore<User>>()
.Setup(x => x.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(user);
var manager = new ApplicationUserManager(store.Object);
controller.UserManager:
controller.UserManager = manager;
:
user , ClientId, .