How do i mock UserManager and RoleManager for unit test - c#

I have mocked abstract class to test concrete method of a class as following.
var mock = new Mock<BaseTestController>();
mock.CallBase = true;
var ta = mock.Object;
ta.ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() };
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);
ta.Request.SetOwinContext(owinMock.Object);
var result = await ta.ActivateDeactive("test#user.com", true);
Problem:
My abstract class use Entity Framework 6 and Asp.Net Identity UserManager and RoleManager as following
public TestUserManager UserService
{
get
{
return _userService ?? Request.GetOwinContext().GetUserManager<TestUserManager>();
}
private set
{
_userService = value;
}
}
public TestRoleManager RoleService
{
get
{
return _roleService ?? Request.GetOwinContext().Get<TestRoleManager>();
}
private set
{
_roleService = value;
}
}
How i can mock TestUserManager and TestRoleManager in my above mocking code?
I tried the following way but couldn't get the way to hook it up with controllerContext.
var userStore = new Mock<IUserStore<TestUser>>();
var userManager = new TestUserManager(userStore.Object);
Answer to question asked below by Aleksey L.
This is how TestUserManager derives UserManaer and implement.
public class TestUserManager : UserManager<TestUser>
{
public TestUserManager(IUserStore<TestUser> store)
: base(store)
{
}
public static TestUserManager Create(IdentityFactoryOptions<TestUserManager> options, IOwinContext context)
{
TestUserManager manager = new TestUserManager(new UserStore<TestUser>(context.Get<AuthContext>()));
setValidationRules(manager);
IDataProtectionProvider dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider == null)
dataProtectionProvider = new DpapiDataProtectionProvider();
manager.UserTokenProvider = new DataProtectorTokenProvider<TestUser>(dataProtectionProvider.Create("ASP.NET Identity")) { TokenLifespan = TimeSpan.FromDays(expiryTime) };
return manager;
}
public static TestUserManager CreateLocal(AuthContext context)
{
TestUserManager manager = new TestUserManager(new UserStore<TestUser>(context));
setValidationRules(manager);
IDataProtectionProvider dataProtectionProvider = new DpapiDataProtectionProvider();
manager.UserTokenProvider = new DataProtectorTokenProvider<TestUser>(dataProtectionProvider.Create("ASP.NET Identity"));
return manager;
}
private static void setValidationRules(ApplicationUserManager manager)
{
manager.UserValidator = new UserValidator<TestUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
manager.PasswordValidator = new ApplicationPasswordValidator
{
RequiredLength = 30,
MaximumCharacters = 30,
RequireNonLetterOrDigit = false,
RequireDigit = true,
RequireLowercase = false,
RequireUppercase = false
};
}
}
Controller Code
public async Task<IHttpActionResult> ActivateDeactive(string studentId, bool active)
{
IdentityResult result;
_accountService = new AccountMgtService(UserService, RoleService);
result = await _accountService.ActiveDeactiveUser(userId, active);
}

Not sure why you're implementing TestUserManager and not just mocking it. Lat's say we have following code in controller:
var owinContext = Request.GetOwinContext();
var userManager = owinContext.GetUserManager<ApplicationUserManager>();
var applicationUser = userManager.FindById("testId");
You can inject mock user store this way:
var owinMock = new Mock<IOwinContext>();
var userStoreMock = new Mock<IUserStore<ApplicationUser>>();
userStoreMock.Setup(s => s.FindByIdAsync("testId")).ReturnsAsync(new ApplicationUser
{
Id = "testId",
Email = "test#email.com"
});
var applicationUserManager = new ApplicationUserManager(userStoreMock.Object);
owinMock.Setup(o => o.Get<ApplicationUserManager>(It.IsAny<string>())).Returns(applicationUserManager);
ta.Request.SetOwinContext(owinMock.Object);

Related

Unit testing automapper to return count of users in a role

I would like to unit test this Controller. It returns the name of the role and the count of users that belong to that role:
[HttpGet]
[EnableQuery]
public IEnumerable<RoleDto> Get()
{
var roles = dbContext.Roles.ToList();
return roles.Select(r =>
{
var dto = mapper.Map<RoleDto>(r);
dto.UserCount = dbContext.UserRoles.Count(x => x.RoleId == r.Id);
return dto;
}).ToList();
}
And here is my test - The DTO is always null and later throws an exception. I am unable to map this properly.
It is a simple unit test that creates a user, creates roles and add the user to those roles.
It then checks if a user has been added to that role.
[Test]
public async Task Get_Should_Return_List_OfRoles()
{
TestSetup();
var mapperMock = new Mock<IMapper>();
IdentityRole role = null;
mapperMock.Setup(u => u.Map<RoleDto>(It.IsAny<IdentityRole>()))
.Callback<object>(inputargs => role = inputargs as IdentityRole);
var roleManagerWrapperMock = new Mock<IRoleManagerWrapper>();
var admin = new IntentUser
{
UserName = "Administrator2",
Email = "admin2#intent2.app",
EmailConfirmed = true,
IsEnabled = true,
IsSystemUser = true
};
var adminRole = new IdentityRole()
{
Name = "Admin"
};
var managerRole = new IdentityRole()
{
Name = "Manager"
};
ApplicationDbContext.Users.Add(admin);
ApplicationDbContext.Roles.Add(managerRole);
ApplicationDbContext.Roles.Add(adminRole);
ApplicationDbContext.SaveChanges();
var adminRoleAdded = new IdentityUserRole<string>()
{
RoleId = adminRole.Id,
UserId = admin.Id
};
var managerRoleAdded = new IdentityUserRole<string>()
{
RoleId = managerRole.Id,
UserId = admin.Id
};
ApplicationDbContext.UserRoles.Add(adminRoleAdded);
ApplicationDbContext.UserRoles.Add(managerRoleAdded);
ApplicationDbContext.SaveChanges();
var sut = new RolesController(roleManagerWrapperMock.Object, ApplicationDbContext, mapperMock.Object);
var result = sut.Get();
foreach (var roleDto in result)
{
Assert.AreEqual(roleDto.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);
}
As mentioned in the comments, you can use an actual mapper instead of trying to mock it.
//...
//Configure mapping just for this test but something like this
//should be in accessible from your composition root and called here.
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<RoleDto, IdentityRole>();
cfg.CreateMap<IdentityRole, RoleDto>();
});
IMapper mapper = config.CreateMapper();
// or
//IMapper mapper = new Mapper(config);
//...
Reference Automapper: Getting Started Guide

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);
}

Moq setup returns null object when the method is called by a UnitTest

Test Setup
Mock gives null object when the test hits the method inside the controller
My controller's constructor has two dependencies which I mocked. While running the test for CheckOut it is giving null object in the result. I am using AutoMapper to map between Model objects and Business
[Fact]
public void CheckOutSomethingsTest()
{
Mock<ICheckoutService> checkoutServiceMock = new Mock<ICheckoutService>();
Mock<IMapper> mapperMock = new Mock<IMapper>();
checkoutServiceMock.Setup(c => c.CheckoutSomethings(new CheckOutSomethingsInput
{
SecretKey = "SecureKey",
UserId = 100,
SomethingIds = new List<int> { 10001, 1002, 1003 }
}))
.Returns<List<CheckedOutSomething>>((o) => new List<CheckedOutSomething>
{
new CheckedOutSomething { Id = 10001, Remarks = "Success" },
new CheckedOutSomething { Id = 10002, Remarks = "Success" }
});
var configuration = new MapperConfiguration(cfg =>
{
cfg.AddSomething(new AutoMapperBusinessToEntitiesSomething());
cfg.AddSomething(new AutoMapperModelsToBusinessSomething());
});
var mapper = new Mapper(configuration);
var controller = new SomethingsController(checkoutServiceMock.Object, mapper);
var result = controller.CheckOut(
new CheckOutSomethingInputModel
{
UserId = 100,
SomethingIds = new List<int> { 10001, 10002, 10003 }
});
Assert.IsType<OkObjectResult>(result.Result);
Assert.Equal(2, result.Value.Count);
}
Service
Constructor
public ProfilesController(ICheckoutService checkoutService, IMapper mapper)
{
this.checkoutService = checkoutService;
this.mapper = mapper;
}
Method
[HttpPost]
[Route("checkout")]
public ActionResult<List<CheckedOutSomethingModel>>
CheckOut([FromBody] CheckOutSomethingInputModel checkoutInput)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var input = mapper.Map<CheckOutSomethingsInput>(checkoutInput);
var output = mapper.Map<List<CheckedOutSomethingModel>>
(checkoutService.CheckoutSomethings(input));
return Ok(output);
}
I cannot figure out what am I doing wrong
#Fabio Many Thanks Is it like this
checkoutServiceMock.Setup(c => c.CheckoutSomethings(It.IsAny<CheckOutSomethingsInput>()))
.Returns(new List<CheckedOutSomething>
{
new CheckedOutSomething { Id = 10001, Remarks = "Success" },
new CheckedOutSomething { Id = 10002, Remarks = "Success" }
});
I actually did and It worked, Thanks Again

Identity EmailService not firing when attempting to send confirmation email

I've been modifying my implementation of ASP.Net Identity in my WebForms application. My modifications have caused my EmailService's SendAsync function to not fire and i'm not sure why. The only thing i can think of is how i am instantiating the UserManager on the register page. Before i was doing var manager = Context.GetOwinContext().GetUserManager(); and now i'm doing var manager = new DecisionLogicIdentity.ApplicationUserManager(userStore);. I am setting the EmailService in the Create function of the UserManager (manager.EmailService = new EmailService();). The SendGrid implementation was working prior to my change to how i call the UserManager. Does anyone have any idea what i am missing here?
Register.aspx.cs:
protected void CreateUser_Click(object sender, EventArgs e)
{
var context = HttpContext.Current.GetOwinContext().Get<DecisionLogicIdentity.ApplicationDbContext>();
var userStore = new DecisionLogicIdentity.UserStore<DecisionLogicIdentity.ApplicationUser>(context)
{
CompanyId = Int32.Parse(CompanyId.Text)
};
var manager = new DecisionLogicIdentity.ApplicationUserManager(userStore);
var signinManager = new DecisionLogicIdentity.ApplicationSignInManager(manager, HttpContext.Current.GetOwinContext().Authentication);
var provider = new DpapiDataProtectionProvider("SampleAppName");
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(provider.Create("SampleTokenName"));
var user = new DecisionLogicIdentity.ApplicationUser()
{
CompanyId = Int32.Parse(CompanyId.Text),
UserName = Email.Text,
Email = Email.Text,
IsExpired = false,
IsDeleted = false
};
IdentityResult result = manager.Create(user, Password.Text);
if (result.Succeeded)
{
user = userStore.FindByEmailAsync(user.Email).GetAwaiter().GetResult();
string code = manager.GenerateEmailConfirmationToken(user.Id);
string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking here.");
//signinManager.SignIn(user, isPersistent: false, rememberBrowser: false);
//signinManager.PasswordSignIn(Email.Text, Password.Text, true, shouldLockout: true);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
ErrorMessage.Text = result.Errors.FirstOrDefault();
}
}
EmailService:
public class EmailService : IIdentityMessageService
{
public async Task SendAsync(IdentityMessage message)
{
await configSendGridasync(message);
}
// Use NuGet to install SendGrid (Basic C# client lib)
private async Task configSendGridasync(IdentityMessage message)
{
SendGridClient client = new SendGridClient(ConfigurationManager.AppSettings["SendGrid--APIKey"].ToString());
var msg = MailHelper.CreateSingleEmail(new SendGrid.Helpers.Mail.EmailAddress("someemail#somedomain.com"),
new SendGrid.Helpers.Mail.EmailAddress(message.Destination),
message.Subject,
message.Body,
message.Body);
msg.Attachments = null;
await client.SendEmailAsync(msg);
}
}
ApplicationUserManager:
public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
public ApplicationUserManager(IUserStore<ApplicationUser, int> store)//, IIdentityMessageService emailService)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(
new DecisionLogicIdentity.UserStore<ApplicationUser>(
context.Get<ApplicationDbContext>() as DatabaseContext));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromSeconds(Int32.Parse(ConfigurationManager.AppSettings["UserLockoutMinutes"].ToString()));
manager.MaxFailedAccessAttemptsBeforeLockout = Int32.Parse(ConfigurationManager.AppSettings["UserMaxLoginAttempts"].ToString());
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser, int>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser, int>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
var provider = new DpapiDataProtectionProvider("SampleAppName");
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(provider.Create("SampleTokenName"));
}
return manager;
}
}
In case anyone needs the answer to this, I was able to get this functioning by modifying my UserManager like so:
public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
public ApplicationUserManager(IUserStore<ApplicationUser, int> store, IIdentityMessageService emailService)
: base(store)
{
this.EmailService = emailService;
}
...
And when instantiating the UserManager:
var manager = new ApplicationUserManager(userStore, new EmailService());

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
//...
}
}

Categories