stackuser
stackuser

Reputation: 672

how to change the value of user.identity.name

I think this is a very fundamental question - but i am not sure how to do it.

I am trying to test an application with different user login ID's (because these users have different roles).The application uses the login information of the system user and has no login of its own. The user.identity.name is used to get the value. However I would like to override this value to test for different user logins. How can I do this?

Upvotes: 3

Views: 8000

Answers (4)

Arya Mohanan
Arya Mohanan

Reputation: 769

Simpliest solution is when user updates name - log him out, and ask for login. its work for me

Upvotes: -1

rbassett
rbassett

Reputation: 391

I'm wanting to do the same.

My thoughts are to create a "change identity" page (only accessible by those with admin roles in my application). They can then choose to be a different person / role for the purpose of testing the application.

Each page in my application tests to see if a session set user id and role is valid (set on first use of the application) and loads the page to show the information / functionality that that user / role is meant to see. So this "change identity" function would set the session user id and role to that of the user under test, and allow the person testing to behave as if they are the other person. Also providing a reset option to reset yourself back to you.

Upvotes: 0

Bob The Janitor
Bob The Janitor

Reputation: 20802

you could always mock it with something like Moq

Mock<ControllerContext> ControllerContextMock;
string UserName = "TestUser";
ControllerContextMock = new Mock<ControllerContext>();
ControllerContextMock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(UserName); 

this is how I do my unit/behavior testing

per my Comment below I'm adding a wrapper around the get user Name

public string OverideName;

private string GetUserName()
{
    string name;
    if(OverideName != null && OverideName.Langth>0)
    {
       name = OverideName;
    }else
    {
       name = User.Identity.Name;
    }
    return name;
}

For most older asp.net web form testing this is really the only way to test stuff

Upvotes: 1

Papa Burgundy
Papa Burgundy

Reputation: 6467

When you set your authentication ticket, change it there. I'm assuming it's using Forms Auth (logging in as user).

FormsAuthentication.RedirectFromLoginPage("Joe",false);

If using Windows Authentication you could use impersonation.

Another alternative, if using Windows Authentication, is to modify your browser setting to prompt you for a login. Then login as the different user.

Upvotes: 2

Related Questions