Mocking SetPhoneNumberAsync in MVC 5 - asp.net-mvc

I am using Moq framework to mock objects in my project. I want to save the user profile which is calling UserManager.SetPhoneNUmberAsync of AspNet.Identity.
Here is my code:
public async Task<ActionResult> SaveProfile(DistributorViewModel distributorModel)
{
if (ModelState.IsValid)
{
string currentUserId = User.Identity.GetUserId();
distributorModel.UserDetailViewModel.ModifiedDate = System.DateTime.Now;
distributorModel.UserDetailViewModel.ModifiedBy =Guid.Parse( currentUserId);
var isUpdated = this.distributorService.Update(distributorModel.UserDetailViewModel);
IdentityResult result = await UserManager.SetPhoneNumberAsync(currentUserId, distributorModel.UserDetailViewModel.MobileNo);
if (result.Succeeded && isUpdated)
{
Flash.Success(Messages.ProfileUpdatedSuccessfully);
}
else
{
Flash.Error(Messages.ProfileUpdationError);
}
}
return RedirectToAction("Index", distributorModel);
}
Its throwing error on UserManager.SetPhoneNumberAsync.
How can I mock this method?

Something similar to this should work:
var manager = new Mock<UserManager<ApplicationUser>();
manager.Setup(m => m.SetPhoneNumberAsync(userId, "phoneNumber").ReturnsAsync(IdentityResult.Succeeded()).Verifiable();

You can also create class IdentityResultMock which inherited from IdentityResult. Than you can assign Successed property from IdentityResultMock because IdentityResult has protected constructor.
Please refer to my answer here.

Related

How to mock HttpContext in ASP.NET Core [duplicate]

This question already has answers here:
Error trying to create Mock.Of<ControllerContext>() for ASP.Net Core 3.1 Unit Test
(2 answers)
Closed 1 year ago.
I'm trying to mock HttpContext to test my UsersController.
The UsersController inherit from
public abstract class ControllerBase
and HttpContext is a property of ControllerBase
public HttpContext HttpContext { get; }
and here is the method in the UsersContoller, which I want to test
public async Task<IActionResult> Register([FromBody] UserViewModel model)
{
_logger.LogDebug("Register new user");
var user = mapper.Map<User>(model);
user.Company.Active = false;
var result = await userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await userManager.AddToRoleAsync(user, Roles.NO_ACCESS);
//send confirmation email
string confirmationToken = userManager.GenerateEmailConfirmationTokenAsync(user).Result;
HostString hostString = HttpContext.Request.Host; //I need to mock httpcontext for this
this.mailSender.SendConfirmationMailAsync(user, hostString, confirmationToken);
return Ok();
}
else
{
_logger.LogInformation("User could not be registered Errors:");
result.Errors.ToList().ForEach(e => _logger.LogInformation(e.Description));
return BadRequest(result.Errors);
}
}
this is my BaseTestContoller, in which setup for tests is initialized
[SetUp]
public void Setup()
{
var dbContext = CreateDbContext();
CreateUserManager();
CreateMailSender(dbContext);
CreateMockImapper();
CreateMockIlogger();
usersController = new Mock<UsersController>(
userManagerMock.Object,
new CompanyService(dbContext),
mailSenderMock,
new Mock<IConfiguration>().Object,
iMapperMock.Object,
iLoggerFactoryMock.Object);
}
i've tried many options, but it wasn't successful therefor it would be nice if someone could help me.
Thanks in advance
UPDATE
usersController = new Mock<UsersController>(
userManagerMock.Object,
new CompanyService(dbContext),
mailSenderMock,
new Mock<IConfiguration>().Object,
iMapperMock.Object,
iLoggerFactoryMock.Object);
var conterllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { } };
HostString host = new HostString("test.de");
conterllerContext.HttpContext.Request.Host = host;
usersController.Setup(c => c.HttpContext).Returns(conterllerContext.HttpContext);
Now i have a problem with setting up.
userController.setup returns this msg :
System.NotSupportedException : Unsupported expression: c => c.HttpContext
Non-overridable members (here: ControllerBase.get_HttpContext) may not be used in setup / verification expressions.
You can use ControllerContext to set the context to be DefaultHttpContext which you can modify to your needs.
var ctx = new ControllerContext() { HttpContext = new DefaultHttpContext()};
var tested = new MyCtrl();
tested.ControllerContext = ctx;
Can't you make a mock service for getting the host address (I am not really familiar with mock libraries).
Something like this:
class IHostService {
string GetHost();
}
public class HostService {
// create constructor with httpcontextaccessor
public string GetHost() {
return _httpContextAccessor.HttpContext.Request.Host;
}
}
public class MockHostService {
public string GetHost() {
return "test.de";
}
}
and in your mock class you can probably add this service just like you added mailSenderMock. And in your controller you use string host = _hostService.GetHost().

Getting identity from another method in the same class

Into class I get logged user like
public static GetUserById_Result GetUser(string userId)
{
GetUserById_Result user = new GetUserById_Result();
try
{
using (EF.SSMA oContext = new EF.SSMA())
{
user = oContext.GetUserById(userId).FirstOrDefault();
}
}
catch (Exception)
{
throw;
}
return user;
}
So it runs fine. But in the same class I want to acces user value into another method
public static List<GetUsers_Result> SelectAll()
{
List<GetUsers_Result> lstResult = new List<GetUsers_Result>();
try
{
using (EF.SSMA oContext = new EF.SSMA())
{
lstResult = oContext.GetUsers().Where().ToList();
}
}
catch (Exception ex)
{
throw ex;
}
return lstResult;
}
What I need to do to achieve that?, into controller is really simple I just do this:
var users = User.Identity.GetUserId();
GetUserById_Result currentUser = UserClass.GetUser(users);
var role = currentUser.BranchOfficeId;
But how can I acces it in the same class' I try to call GetUserId with
System.Web.HttpContext.Current.User.Identity.GetUserId();
but it just mark HttpContext in red and say "Cannot resolve symbol 'HttpContext'"
My target is to call only users who BranchOfficeId = user.BranchOfficeId
Help is very appreciated. Regards
If i understand your question well, make sure that you already installed the package Microsoft.Owin.Host.SystemWeb and add using System.Web, then use directely User.Identity.GetUserId()
The reason you can do this in the controller is because Controller has an HttpContext property, which has been created with the details of the current request, including the identity of the current user.
If you want to access the user from another class, you need to pass the user as an argument to your method. As an example:
using System.Security.Principal;
public class SomeClass
{
public void SomeMethod(IPrincipal user)
{
// Whatever you need
}
}
Then in your controller:
var someClass = new SomeClass();
someClass.SomeMethod(HttpContext.User);
However, if you're only interested in the user's name, then you can actually just pass a string instead:
public class SomeClass
{
public void SomeMethod(string username)
{
// Whatever you need
}
}
Then in your controller:
var someClass = new SomeClass();
someClass.SomeMethod(HttpContext.User.Identity.Name);

ASP.NET MVC, HttpContext.Current is null while mocking a request

public async Task <ActionResult>Select(DWorkingTimeSelection dto) {
var session = HttpUtils.GetSeesion<User>("USER");
}
public static T GetSeesion<T>(string key) where T : class
{
if (HttpContext.Current == null)
{
return default(T);
}
return HttpContext.Current.Session[key] as T;
}
public async Task <ActionResult>Select(DWorkingTimeSelection dto) {
var session = HttpUtils.GetSeesion<User>("USER");
}
public static T GetSeesion<T>(string key) where T : class
{
if (HttpContext.Current == null)
{
return default(T);
}
return HttpContext.Current.Session[key] as T;
}
I use nunti to mock a request.
And I add the SessionStateItemCollection to the Controller 's ControllerContext .
I found that the HttpContext.Current is null but the Controller 's Session[]
is not null because it get from the Controller 's ControllerContext .
So what should I do to avoid the HttpContext.Current is null while mocking a request
You can mock the HttpContext:
public static HttpContext FakeHttpContext(HttpRequest request)
{
var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
var httpContext = new HttpContext(request, httpResponce);
var sessionContainer = new HttpSessionStateContainer(
"id",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
10,
true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc,
false);
httpContext.Items["AspSession"] =
typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null).Invoke(new object[] { sessionContainer });
return httpContext;
}
[TestMethod]
public void ActionTest()
{
var request = new HttpRequest(string.Empty, "url to the action that you are testing", string.Empty)
{
RequestType = "GET"
};
HttpContext.Current = FakeHttpContext(request);
var controller = new YourController();
//You need the get a Result property since it is an async action
var result = controller.ActionToTest(//the parameters that your action expects).Result;
Assert.IsNotNull(result);
}
EDIT (answering the questions in your comment):
In order tot get a session you need to call HttpContext.Current.Session and not the HttpContext.Current.Session["id"] because HttpContext.Current.Session["id"] tries to get an id key from your session.
Once you store it there it will be available through this call. You can test it:
HttpContext.Current.Session["id"] = 5;
Assert.AreEqual(HttpContext.Current.Session["id"],5);
Regarding the httpContext.Items statement:
(From MSDN)HttpContext.Items is a key/value collection that can be used to organize and share data between an IHttpModule interface and an IHttpHandler interface during an HTTP request.
The statement that you are asking for, simply crates a new HttpSessionState object by using reflection (because it has only internal constructors) associates it with the HttpSessionStateContainer that you created earlier and stores it in HttpContext.Items under AspSession. And an interesting thing is that HttpContext.Current.Session actually is a shortcut to HttpContext.Items["AspSession"]. So the assignment of HttpSessionState object to the AspSession key is the on that makes HttpContext.Current.Session to work.
Well,after mocking the HttpContext as Alex Art said .
Calling the following method will be fine.
var sessionItems = new SessionStateItemCollection();
sessionItems["SessionKey"] = new MyCustomObject();
SessionStateUtility.AddHttpSessionStateToContext(fakeHttpContext,
new HttpSessionStateContainer(SessionNameStorage.Suser,
sessionItems,
new HttpStaticObjectsCollection(),
20000,
true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc,
false
));

Async ctp MVC4 and workflows

I have the below code which calls a workflow. I am wondering if I can changed the controller to be asynchronous using the async ctp.
public ActionResult Index()
{
var input = new Dictionary<string, object>();
input["ViewData"] = this.ViewData;
var userState = "BeginInvoke example";
var invoker = new WorkflowInvoker(HelloMvcDefinition);
Task workflowTask = Task.Factory.FromAsync<IDictionary<string, object>>(
invoker.BeginInvoke(input, WorkflowCompletedCallback, userState),
invoker.EndInvoke);
workflowTask.Wait();
return View();
}
I have tried this but I cannot seem to get it to work:
public async Task<ActionResult> Index()
{
var input = new Dictionary<string, object>();
input["ViewData"] = this.ViewData;
var userState = "BeginInvoke example";
var invoker = new WorkflowInvoker(HelloMvcDefinition);
Task workflowTask = Task.Factory.FromAsync<IDictionary<string, object>>(
invoker.BeginInvoke(input, WorkflowCompletedCallback, userState),
invoker.EndInvoke);
await workflowTask;
return View();
}
Unfortunately the view does not seem to work. Any ideas on what I am doing wrong?
EDIT
After taking advice I have changed the method to this
public class HelloController : AsyncController
{
private static readonly HelloWorkflow HelloMvcDefinition = new HelloWorkflow();
public Task<ViewResult> Index()
{
var input = new Dictionary<string, object>();
input["ViewData"] = ViewData;
const string userState = "BeginInvoke example";
var invoker = new WorkflowInvoker(HelloMvcDefinition);
return Task.Factory.FromAsync<IDictionary<string, object>>(
invoker.BeginInvoke(input, WorkflowCompletedCallback, userState),
invoker.EndInvoke).ContinueWith(t => View());
}
static void WorkflowCompletedCallback(IAsyncResult result)
{
}
}
Which works fine so the problem must be how I am using the async keyword.
Thanks
We can use the TAP pattern for invoking windows workflow as follows -
(Details are mentioned in my blog post http://tweetycodingxp.blogspot.com/2013/06/invoke-workflow-wf-using-task-based.html)
public async Task<ActionResult> Index(string id)
{
var wfInputArgs = new Dictionary<string, object>
{
...
};
var wfOutputArgs = await Task<IDictionary<string, object>>.Factory.StartNew(
() => WorkflowInvoker.Invoke(new MyWorkflow(), wfInputArgs));
var result = wfOutputArgs["Output1"] as IEnumerable<Class1>;
...
return View(model);
}
Derive from AsyncController instead of Controller.
EDIT: You may also be experiencing a known bug where ASP.NET MVC4 will hang if the action returns a completed Task. You can work around this bug by adding await Task.Yield(); at the top of the action method.
On an unrelated note, this code is more efficient (and shorter, too):
var workflowTask = Task.Factory.FromAsync(invoker.BeginInvoke, invoker.EndInvoke,
input, userState);

Unit Testing Custom Model Binder - Fake HttpContext Issue

I have the following unit test defined to test my model binder:
[TestMethod]
public void DateTime_Works() {
// Arrange
var controllerContext = FakeContext.GetAuthenticatedControllerContext(new Mock<Controller>().Object, "TestAdmin");
var values = new NameValueCollection {
{ "Foo.Date", "12/02/1964" },
{ "Foo.Hour", "12" },
{ "Foo.Minute", "00" },
{ "Foo.Second", "00" }
};
var bindingContext = new ModelBindingContext() { ModelName = "Foo", ValueProvider = new NameValueCollectionValueProvider(values, null) };
var binder = new DateAndTimeModelBinder();
// Act
var result = (DateTime)binder.BindModel(controllerContext, bindingContext);
// Assert
Assert.AreEqual(DateTime.Parse("1964-12-02 12:00:00"), result);
}
Here is the FakeContext class:
public static class FakeContext {
public static HttpContextBase GetHttpContext(string username) {
var context = new Mock<HttpContextBase>();
context.SetupGet(ctx => ctx.Request.IsAuthenticated).Returns(!string.IsNullOrEmpty(username));
return context.Object;
}
public static ControllerContext GetControllerContext(Controller controller) {
return GetAuthenticatedControllerContext(controller, null);
}
public static ControllerContext GetAuthenticatedControllerContext(Controller controller, string username) {
var httpContext = GetHttpContext(username);
return new ControllerContext(httpContext, new RouteData(), controller);
}
}
Within my model binder i call a utility method which has the following line in it:
HttpContext.Current.User.Identity.IsAuthenticated
This seems to always return false even when I pass a username in. I was wondering how the GetHttpContext method can be modified to mock this out aswell.
I'd appreciate the help. Thanks
You are mocking the IsAuthenticated property of the Request and not of the User Identity. Your mock is indicating that the request has been authenticated, but has nothing to do with the identity authentication.
Changing your mock up a little should fix your problem.
var identityMock = new Mock<IIdentity>();
identityMock.SetupGet( i => i.IsAuthenticated ).Returns( !string.IsNullOrEmpty(username));
var userMock = new Mock<IPrincipal>();
userMock.SetupGet( u => u.Identity ). Returns( identityMock.Object );
var context = new Mock<HttpContextBase>();
context.SetupGet( ctx => ctx.User ).Returns( userMock.Object );
Edit The more I thought about it the more I felt these mocks needed to be setup seperatly
Note, I have not executed this code. It should get you what you need however.
MSDN for Request.IsAuthenticated
http://msdn.microsoft.com/en-us/library/system.web.httprequest.isauthenticated.aspx
MSDN for User.Identity.IsAuthenticated
http://msdn.microsoft.com/en-us/library/system.security.principal.iidentity.isauthenticated.aspx
Hope this helps.
You could use Moq and follow the advice found here:
Moq: unit testing a method relying on HttpContext

Resources