1

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";
ca9163d9
  • 27,283
  • 64
  • 210
  • 413
  • I believe it is. However, I'm not sure. Have you tried configure the authentication on the test project? You may sign the user inside the constructor of the `TestClass`. – Fabio Sep 03 '15 at 21:15
  • Can you give some details on how to sign in in the test class? It seems need to add all the dependent asp.net dlls too? – ca9163d9 Sep 03 '15 at 21:50

2 Answers2

0

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.

Community
  • 1
  • 1
Niels V
  • 1,005
  • 8
  • 11
0

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!

Hernan Guzman
  • 1,235
  • 8
  • 14