简体   繁体   中英

Test an Asp.Net Controller action method which uses User.Identity.Name?

I have the following test method for an Asp.Net controller action method.

[TestMethod]
public void Get()
{
    var controller = new MyController();
    var result = controller.GetAListOfRecords();
    Assert.IsNotNull(result);
    Assert.IsTrue(result.Count() > 0);
}

And the action is

[Authorize(Roles = "Users")]
public IQueryable<MyModel> GetAListOfRecords()
{
    var user = User.Identity.Name; // null when called from the test method
    var q = from t in ........
            select t;
    return return string.IsNullOrEmpty(user) ? Enumerable.Empty<MyModel>().AsQueryable() : q;
}

However, the var user = User.Identity.Name will not get current user name in the test class (it will actually be assigned an empty string). Is it possible to set user in the test method?

Update: I tried the following in the test class but .....Identity.Name is read-only.

controller.RequestContext.Principal.Identity.Name = @"mdynycmas\wangyi";

Actually, you're using the User property on your Controller object. This property is using the underlying HttpContext.Current. You need to mock the HttpContextBase and return a test user, see for instance How to mock Controller.User using moq .

You need to implement some mocks in your unit tests. Also I suggest you to remove your direct dependency of HttpContext, and better create a wrapper object instead, so you can mock it easily. See more information in this link about this approach.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM