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";