Returning users from mocked ApplicationUserManager.Users - c#

I am trying to mock ApplicationUserManager.Users so that I can test a controller method. My controller is
public class ManageController : Controller
{
private readonly ApplicationUserManager userManager;
public ManagerController(ApplicationUserManager userManager)
{
this.userManager = userManager;
}
// The method being tested
public ActionResult ListUsers()
{
// I want this to return my mocked user list
var users = this.userManager.Users.ToList();
// Do other stuff
}
}
My test method is
[TestMethod]
public void ListUsersGet_ShouldSucceed()
{
var users = new List<ApplicationUser>
{
new ApplicationUser { Id = "1", FirstName = "Test", LastName = "User" }
}.AsQueryable();
Mock<DbSet<ApplicationUser>> dbSet = new Mock<DbSet<ApplicationUser>>();
dbSet.As<IQueryable<ApplicationUser>>().Setup(e => e.ElementType).Returns(users.ElementType);
dbSet.As<IQueryable<ApplicationUser>>().Setup(e => e.Expression).Returns(users.Expression);
dbSet.As<IQueryable<ApplicationUser>>().Setup(e => e.GetEnumerator()).Returns(users.GetEnumerator());
dbSet.As<IQueryable<ApplicationUser>>().Setup(e => e.Provider).Returns(users.Provider);
Mock<MyContext> context = new Mock<MyContext>();
context.Setup(e => e.Users).Returns(dbSet.Object);
Mock<UserStore<ApplicationUser>> userStore = new Mock<UserStore<ApplicationUser>>(context.Object);
var controller = new ManageController(new ApplicationUserManager(userStore.Object));
var result = controller.ListUsers() as ViewResult;
// Assert some stuff
}
When I step into my controller method, I can see that users is null. It appears that this.userManager.Users isn't returning the users that I tried to set up in my test method.
How can I get this.userManager.Users.ToList() to return my test users?

User manager exposes public virtual IQueryable<TUser> Users { get; } property. Mock the user manager dependency and give that to the controller.
public void _ListUsersGet_ShouldSucceed() {
// Arrange.
var users = new List<ApplicationUser>
{
new ApplicationUser { Id = "1", FirstName = "Test", LastName = "User" }
}.AsQueryable();
//Only mocking this because we need it to initialize manager.
var userStore = Mock.Of<IUserStore<ApplicationUser>>();
var userManager = new Mock<ApplicationUserManager>(userStore);
userManager.Setup(_ => _.Users).Returns(users);
var controller = new ManageController(userManager.Object);
// Act.
var result = controller.ListUsers() as ViewResult;
// Assert some stuff
}
Check the Quick start documentation to get more acquainted with the mocking framework

Related

Missing type map configuration or unsupported mapping on IdentityRole

I am writing unit tests and this mapper is causing me grief again. I understood from a previous post that I cannot Mock the mapper, i have to use it straight away. So I have created maps but it says missing type map configuration.
public RoleDto GetSingle([FromRoute] string id)
{
var r = roleManagerWrapper.GetSingleRole(id);
return mapper.Map<RoleDto>(r);
}
It breaks when it tries to map the object. Is there any special mapping for Task <IdentityRole> that needs to be implemented?
public async Task<IdentityRole> GetSingleRole(string roleId)
{
var role = await this.roleManager.Roles.SingleOrDefaultAsync(r => r.Id == roleId);
return role;
}
Here is my test that only counts the number of roles that are created.
[Test]
public async Task Get_Single()
{
TestSetup();
var roleManagerWrapperMock = new Mock<IRoleManagerWrapper>();
var adminRole = new IdentityRole()
{
Name = "Admin",
Id = "4a8de423-5663-4831-ac07-7ce92465b008"
};
var managerRole = new IdentityRole()
{
Name = "Manager",
Id = "40f74162-3359-4253-9b5a-ad795b328267"
};
ApplicationDbContext.Roles.Add(managerRole);
ApplicationDbContext.Roles.Add(adminRole);
ApplicationDbContext.SaveChanges();
var sut = new RolesController(roleManagerWrapperMock.Object, ApplicationDbContext, Mapper);
var result = sut.GetSingle("4a8de423-5663-4831-ac07-7ce92465b008");
Assert.AreEqual(result.UserCount, 1);
}
protected void TestSetup(string databaseName = null)
{
if (databaseName == null)
{
databaseName = GetTestName();
}
TestCleanup();
ServiceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
dbContextOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName)
.UseInternalServiceProvider(ServiceProvider)
.Options;
ApplicationDbContext = new ApplicationDbContext(dbContextOptions);
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RoleDto, IdentityRole>();
cfg.CreateMap<IdentityRole, RoleDto>();
cfg.CreateMap<CreateRoleDto, IdentityRole>().ReverseMap();
cfg.CreateMap<UpdateRoleDto, IdentityRole>().ReverseMap();
});
Mapper = config.CreateMapper();
}
The action needs to be refactored to use proper asyn syntax since GetSingleRole returns Task<IdentityRole>
public Task<RoleDto> GetSingle([FromRoute] string id) {
IdentityRole r = await roleManagerWrapper.GetSingleRole(id);
return mapper.Map<RoleDto>(r);
}
And the test updated accordingly
[Test]
public async Task Get_Single() {
//Arrange
TestSetup();
var roleManagerWrapperMock = new Mock<IRoleManagerWrapper>();
//...omitted for brevity
var sut = new RolesController(roleManagerWrapperMock.Object, ApplicationDbContext, Mapper);
//Act
RoleDto result = await sut.GetSingle("4a8de423-5663-4831-ac07-7ce92465b008");
//Assert
Assert.AreEqual(result.UserCount, 1);
}

Mock Async method on Service using Moq

I am working in a .Net Core API. I wish to unit test the GetArtists method on the ArtistsController.
CODE
Here is my controller code:
[Route("artists")]
public class ArtistsController : Controller
{
private readonly IPermissionsService _permissionsService;
private readonly IArtistsService _artistsService;
private readonly ILogger<ArtistsController> _logger;
public ArtistsController(IPermissionsService permissionsService, IArtistsService artistsService, ILogger<ArtistsController> logger)
{
_permissionsService = permissionsService ?? throw new ArgumentNullException(nameof(permissionsService));
_artistsService = artistsService ?? throw new ArgumentNullException(nameof(artistsService));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
[HttpGet]
public async Task<IActionResult> GetArtists()
{
var permissions = await _permissionsService.GetPermissionsAsync(HttpContext);
var artists = _artistsService.GetAllArtists(permissions.UserId, permissions.IsAdministrator);
return Ok( new { artists });
}
}
And here is the test method I am writing:
[TestClass]
public class ArtistsControllerTests
{
private readonly Mock<IPermissionsService> _mockPermissionsService = new Mock<IPermissionsService>();
private readonly Mock<IArtistsService> _mockArtistsService = new Mock<IArtistsService>();
private readonly Mock<ILogger<ArtistsController>> _mockLogger = new Mock<ILogger<ArtistsController>>();
public void Setup()
{
_mockArtistsService.Reset();
_mockPermissionsService
.Setup(service => service.GetPermissionsAsync(It.IsAny<HttpContext>()))
.Returns(Task.FromResult(new Permissions { UserId = "112233", IsAdministrator = false }));
_mockArtistsService.Setup(service => service.GetAllArtists(It.IsAny<string>(), false)).Returns(new ArtistCardDtoCollection());
}
[TestMethod]
public async Task GetArtists_ReturnsOKStatusCode()
{
// arrange
var artistsController = new ArtistsController(_mockPermissionsService.Object, _mockArtistsService.Object, _mockLogger.Object);
// act
var getArtistsResult = await artistsController.GetArtists();
var okResult = getArtistsResult as OkObjectResult;
// assert
Assert.IsInstanceOfType(okResult, typeof(OkObjectResult));
}
}
Here is the IPermissionsService and the Permissions class.
public interface IPermissionsService
{
Task<Permissions> GetPermissionsAsync(HttpContext httpContext);
}
public class Permissions
{
public string UserId { get; set; }
public bool IsAdministrator { get; set; }
}
When I run that, I get the following error:
Project.ArtistsControllerTests.GetArtists_ReturnsOKStatusCode threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
When debugging, I found out that var permissions = await _permissionsService.GetPermissionsAsync(HttpContext); returns null.
I must have an issue with the way I am mocking that:
_mockPermissionsService
.Setup(service => service.GetPermissionsAsync(It.IsAny<HttpContext>()))
Why wouldn't the above work?
ArtistsControllerTests.Setup() is not being invoked so the mocks are not being setup before the test is exercised.
Therefore when the test is exercised they will return null.
Your setup code is correct, it just is not getting called.
either change that Setup method to a constructor
public ArtistsControllerTests() {
_mockArtistsService.Reset();
_mockPermissionsService
.Setup(service => service.GetPermissionsAsync(It.IsAny<HttpContext>()))
.Returns(Task.FromResult(new Permissions { UserId = "112233", IsAdministrator = false }));
_mockArtistsService.Setup(service => service.GetAllArtists(It.IsAny<string>(), false)).Returns(new ArtistCardDtoCollection());
}
or adorn the method with [TestInitilize] attribute
[TestInitialize]
public void Setup() {
_mockArtistsService.Reset();
_mockPermissionsService
.Setup(service => service.GetPermissionsAsync(It.IsAny<HttpContext>()))
.Returns(Task.FromResult(new Permissions { UserId = "112233", IsAdministrator = false }));
_mockArtistsService.Setup(service => service.GetAllArtists(It.IsAny<string>(), false)).Returns(new ArtistCardDtoCollection());
}
or just move the arrange into the test itself
[TestMethod]
public async Task GetArtists_ReturnsOKStatusCode() {
// arrange
_mockArtistsService.Reset();
_mockPermissionsService
.Setup(service => service.GetPermissionsAsync(It.IsAny<HttpContext>()))
.Returns(Task.FromResult(new Permissions { UserId = "112233", IsAdministrator = false }));
_mockArtistsService.Setup(service => service.GetAllArtists(It.IsAny<string>(), false)).Returns(new ArtistCardDtoCollection());
var artistsController = new ArtistsController(_mockPermissionsService.Object, _mockArtistsService.Object, _mockLogger.Object);
// act
var getArtistsResult = await artistsController.GetArtists();
var okResult = getArtistsResult as OkObjectResult;
// assert
Assert.IsInstanceOfType(okResult, typeof(OkObjectResult));
}

User.Identity.GetUserId() Owin Moq unit test

I have ChangePassword method where I have User.Identity.GetUserId() to find UserId.
Problem: It always return null. Don't understand why.
I read in another post that the GetUserById use below line of code to find Id. I am not sure how do I mock ClaimsTypes.NameIdentifier.
return ci.FindFirstValue(ClaimTypes.NameIdentifier);
ChangePassword method (method to be unit testes)
public async Task<IHttpActionResult> ChangePassword(string NewPassword, string OldPassword)
{
_tstService = new TestService();
IdentityResult result = await _tstService.ChangePassword(User.Identity.GetUserId(), OldPassword, NewPassword);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
Unit Test
var mock = new Mock<MyController>();
mock.CallBase = true;
var obj = mock.Object;
obj.ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() };
obj.Request.SetOwinContext(CommonCodeHelper.mockOwinContext());
IPrincipal user = GetPrincipal();
obj.ControllerContext.RequestContext.Principal = user;
var result = await obj.ChangePassword(dto);
//GetPrincipal
public static IPrincipal GetPrincipal()
{
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
identity.Setup(x => x.Name).Returns("User1#Test.com");
identity.Setup(p => p.IsAuthenticated).Returns(true);
user.Setup(x => x.Identity).Returns(identity.Object);
Thread.CurrentPrincipal = user.Object;
return user.Object;
}
IOwinContext mocking code
public static IOwinContext mockOwinContext()
{
var owinMock = new Mock<IOwinContext>();
owinMock.Setup(o => o.Authentication.User).Returns(new ClaimsPrincipal());
owinMock.Setup(o => o.Request).Returns(new Mock<OwinRequest>().Object);
owinMock.Setup(o => o.Response).Returns(new Mock<OwinResponse>().Object);
owinMock.Setup(o => o.Environment).Returns(new Dictionary<string, object> { { "key1", 123 } });
var traceMock = new Mock<TextWriter>();
owinMock.Setup(o => o.TraceOutput).Returns(traceMock.Object);
var userStoreMock = new Mock<IUserStore<IfsUser>>();
userStoreMock.Setup(s => s.FindByIdAsync("User1#ifstoolsuite.com")).ReturnsAsync(new IfsUser
{
Id = "User1#test.com",
FirstName = "Test",
LastName = "User1",
Email = "User1#test.com",
UserName = "User1#test.com",
});
var applicationUserManager = new IfsUserManager(userStoreMock.Object);
owinMock.Setup(o => o.Get<IfsUserManager>(It.IsAny<string>())).Returns(applicationUserManager);
return owinMock.Object;
}
Your GetPrincipal can be updated to use claims.
public static IPrincipal GetPrincipal() {
//use an actual identity fake
var username = "User1#Test.com";
var identity = new GenericIdentity(username, "");
//create claim and add it to indentity
var nameIdentifierClaim = new Claim(ClaimTypes.NameIdentifier, username);
identity.AddClaim(nameIdentifierClaim);
var user = new Mock<IPrincipal>();
user.Setup(x => x.Identity).Returns(identity);
Thread.CurrentPrincipal = user.Object;
return user.Object;
}
Here is an example that shows how the above approach works.
public partial class MiscUnitTests {
[TestClass]
public class IdentityTests : MiscUnitTests {
Mock<IPrincipal> mockPrincipal;
string username = "test#test.com";
[TestInitialize]
public override void Init() {
//Arrange
var identity = new GenericIdentity(username, "");
var nameIdentifierClaim = new Claim(ClaimTypes.NameIdentifier, username);
identity.AddClaim(nameIdentifierClaim);
mockPrincipal = new Mock<IPrincipal>();
mockPrincipal.Setup(x => x.Identity).Returns(identity);
mockPrincipal.Setup(x => x.IsInRole(It.IsAny<string>())).Returns(true);
}
[TestMethod]
public void Should_GetUserId_From_Identity() {
var principal = mockPrincipal.Object;
//Act
var result = principal.Identity.GetUserId();
//Asserts
Assert.AreEqual(username, result);
}
[TestMethod]
public void Identity_Should_Be_Authenticated() {
var principal = mockPrincipal.Object;
//Asserts
Assert.IsTrue(principal.Identity.IsAuthenticated);
}
}
}
You have some design issues. Creating a concrete TestService will cause problems if it as connecting to an actual implementation. That becomes an integration test. Abstract that dependency as well.
public interface ITestService {
Task<IdentityResult> ChangePassword(string userId, string oldPassword, string newPassword);
}
public abstract class MyController : ApiController {
private ITestService service;
protected MyController(ITestService service) {
this.service = service;
}
public async Task<IHttpActionResult> ChangePassword(string NewPassword, string OldPassword) {
IdentityResult result = await service.ChangePassword(User.Identity.GetUserId(), OldPassword, NewPassword);
if (!result.Succeeded) {
return GetErrorResult(result);
}
return Ok();
}
}
Also you should not mock the System under test. You should mock the dependencies of the SUT. Based on your method to be tested and what you indicated in the comments that MyController is an abstract class, the following test should apply
[TestClass]
public class MyControllerTests {
public class FakeController : MyController {
public FakeController(ITestService service) : base(service) { }
}
[TestMethod]
public void TestMyController() {
//Arrange
var mockService = new Mock<ITestService>();
mockService
.Setup(m => m.ChangePassword(....))
.ReturnsAsync(....);
var controller = new FakeController(mockService.Object);
//Set a fake request. If your controller creates responses you will need this
controller.Request = new HttpRequestMessage {
RequestUri = new Uri("http://localhost/api/my")
};
controller.Configuration = new HttpConfiguration();
controller.User = GetPrincipal();
//Act
var result = await controller.ChangePassword("NewPassword", "OldPassword");
//Assert
//...
}
}

ASP MVC Unit Testing GetUserId()

I have a controller, where I'm calling a userId:
var userId = User.Identity.GetUserId();
This makes my unit test fail, since User is null.
I've tried to set a user in the test method using this method, but User is still null in the controller when the test runs.
var context = new Mock<HttpContextBase>();
var mockIdentity = new Mock<IIdentity>();
context.SetupGet(x => x.User.Identity).Returns(mockIdentity.Object);
mockIdentity.Setup(u => u.Name).Returns("test_userName");
Any hints as to what I'm doing wrong?
The HttpContextBase.User is of type IPrincipal and you have not mocked it. That's why it is returning null when you access it in tests. You can mock it as follows
var controllerContext = new Mock<ControllerContext>();
var principal = new Moq.Mock<IPrincipal>();
principal.Setup(p => p.IsInRole("Administrator")).Returns(true);
principal.SetupGet(x => x.Identity.Name).Returns(userName);
controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);
controller.ControllerContext = controllerContext.Object;
Here is the reference of this code
Okay, so according to this post, you can do it like this:
public class MyController: Controller
{
public Func<string> GetUserId; //For testing
public MyController()
{
GetUserId = () => User.Identity.GetUserId();
}
//controller actions
}
And then instead of caling User.Identity.GetUserId() when you want the user, you just call GetUserId() and mock out the user id in your test:
controller = new MyController()
{
GetUserId = () => "IdOfYourChoosing"
};
You are mocking HttpContextBase but are not passing it to your controller.
Try this pattern:
Class:
public MyClass
{
private readonly HttpContextBase _contextBase;
public MyClass(HttpContextBase contextBase)
{
this._contextBase = contextBase;
}
public void Process()
{
var userId = _contextBase.User.Identity;
}
}
Test:
[Test]
public void MyClass_Test_SO()
{
// arrange
var context = new Mock<HttpContextBase>();
var mockIdentity = new Mock<IIdentity>();
context.SetupGet(x => x.User.Identity).Returns(mockIdentity.Object);
mockIdentity.Setup(u => u.Name).Returns("test_userName");
var sut = new MyClass(context.Object);
// act
sut.Process();
// assert
// ... whatever
}

Struggling with Moq: The following setups were not matched

I'm using Moq for the first time, and I'm struggling with getting the tests to run properly.
I'm trying to moq the Save() method of my service layer.
public void Save(UserViewModel viewModel)
{
// todo: this still doesn't address updating a password. The UserViewModel doesn't contain any Password data.
if (viewModel.Id != Guid.Empty)
{
// The UserId is not empty, we're either updating an existing user
// or we're inserting a new user via sync
var user = _userRepository.GetById(viewModel.Id);
if (user != null)
{
// Looks like we're updating a user because they're already in the database.
_userRepository.Update(_userViewModelToModelMapper.BuildFrom(viewModel));
return;
}
}
// The user is being created, either via a Sync (Guid Exists), or via an Insert (Guid doesn't Exist)
_userRepository.Create(_userViewModelToModelMapper.BuildFrom(viewModel));
}
I've got Three tests, of which, I'm not sure any of them are right. The first two are passing, but the third one fails with
Moq.MockVerificationException : The following setups were not matched:
IUserRepository r => r.Update(It.Is(um => um.Equals()))
Here are the tests.
// PASSES but could be suspect
[Test]
public void ShouldSaveANewUserFromExistingId()
{
// emulating a "sync"
// Setup
var userId = new Guid("81C7FE19-2DB5-4083-BD6A-5433687561F7");
var userModel = new UserModel();
var userViewModel = new UserViewModel {Id = userId};
var userRepository = new Mock<IUserRepository>();
var viewModelToModelMapper = new Mock<IAutoMapper<UserViewModel, UserModel>>();
var modelToViewModelMapper = new Mock<IAutoMapper<UserModel, UserViewModel>>();
// Setup the Mock UserRepository
userRepository.Setup(r => r.Create(It.Is<UserModel>(um => um.Equals(userModel))));
viewModelToModelMapper.Setup(vmm => vmm.BuildFrom(It.Is<UserViewModel>(u => u.Equals(userViewModel))))
.Returns(userModel);
var userService = new UserService(userRepository.Object, viewModelToModelMapper.Object, modelToViewModelMapper.Object);
// Execute
userService.Save(userViewModel);
// Assert
userRepository.VerifyAll();
viewModelToModelMapper.VerifyAll();
}
// PASSES but could be suspect.
[Test]
public void ShouldSaveANewUser()
{
// emulating a standard create
// Setup
var userId = Guid.Empty;
var userModel = new UserModel();
var userViewModel = new UserViewModel { Id = userId };
var userRepository = new Mock<IUserRepository>();
var viewModelToModelMapper = new Mock<IAutoMapper<UserViewModel, UserModel>>();
var modelToViewModelMapper = new Mock<IAutoMapper<UserModel, UserViewModel>>();
// Setup the Mock UserRepository
userRepository.Setup(r => r.Create(It.Is<UserModel>(um => um.Equals(userModel))));
viewModelToModelMapper.Setup(vmm => vmm.BuildFrom(It.Is<UserViewModel>(u => u.Equals(userViewModel))))
.Returns(userModel);
var userService = new UserService(userRepository.Object, viewModelToModelMapper.Object, modelToViewModelMapper.Object);
// Execute
userService.Save(userViewModel);
// Assert
userRepository.VerifyAll();
viewModelToModelMapper.VerifyAll();
}
// FAILS MISERABLY
[Test]
public void ShouldSaveAnExistingUser()
{
// emulating an "Update"
// Setup
var userId = new Guid("0A88AEC2-9F8D-44DE-BD01-3EB9A23C78E3");
var userModel = new UserModel { Id = userId };
var userViewModel = new UserViewModel { Id = userId };
var userRepository = new Mock<IUserRepository>();
var viewModelToModelMapper = new Mock<IAutoMapper<UserViewModel, UserModel>>();
var modelToViewModelMapper = new Mock<IAutoMapper<UserModel, UserViewModel>>();
// Setup the Mock UserRepository
userRepository.Setup(r => r.Update(It.Is<UserModel>(um => um.Equals(userModel))));
viewModelToModelMapper.Setup(vmm => vmm.BuildFrom(It.Is<UserViewModel>(u => u.Equals(userViewModel))))
.Returns(userModel);
var userService = new UserService(userRepository.Object, viewModelToModelMapper.Object, modelToViewModelMapper.Object);
// Execute
userService.Save(userViewModel);
// Assert
userRepository.VerifyAll();
viewModelToModelMapper.VerifyAll();
}
Where am I going wrong with my Moqing?
Seems like in the last case you would need:
userRepository.Setup(r => r.GetById(userId)).Returns(userModel);
Before the userService.Save call. Without it userRepository.GetById will always be null and the update branch will never be taken.

Categories