0

I need to mock current logged in user for testing the following function. This function returns the id of the current logged in user from the Users table in the database.

  public static string CurrentUser()
    {
        string loginuser= System.Web.HttpContext.Current.User.Identity.Name;
        if(loginuser != "")
        {
            using (var cntx = new EdmxEntities())
            {
                return cntx.Users.Where(s => s.Email == loginuser).Select(x => x.Id).FirstOrDefault();
            }
        }
        return loginuser;

    }

(System.Web.HttpContext.Current.User.Identity.Name) This function returns the current logged in username but returns null during testing which throws an Null Reference Exception.

1 Answers1

1

You cannot mock a static method in your typical mocking framework. Depending on something like a database also means you are not unit testing. A unit test cannot depend on dependencies from the infrastructure.

What you could do (and should do IMO) is either:

  • Create an interface that captures the functionality of returning the current user which you can then mock using your framework of choice. This interface (with a matching instance of an implementation of this interface) could then be injected into the class where you need it.
  • Or, when you prefer static methods, ask for the dependency of the current user in the place where you need it and inject it directly from your dependency injection setup.

If you don't care about all this you could probably setup a test database with a connectionString to that in your test project. You would then be integration testing, which has its own merits.

There are however ways to do what you ask (but I would not recommend this), check out this: https://stackoverflow.com/a/12580110/2877982

Aage
  • 5,932
  • 2
  • 32
  • 57