Question

Currently I am using Membership.GetUser() to get the currently logged in username. However this is a static method which is not Mockable. Is there any other way to get the currently logged in username that is mock friendly?

FYI: I am using Moq framework and NUnit.

Was it helpful?

Solution

Generally, in cases like this, you can create a wrapper interface which you can use to stub the GetUser() method.

public interface IMembersipService {
    MembershipUser GetUser();
}

public class MembersipService : IMembersipService
{
    public MembershipUser GetUser() {
        return Membership.GetUser();
    }
}

IMembersipService.GetUser() can be stub/mock based on your need.

Additional note: there are other routines in the Membership class, which you may required to access. You can use the same interface to access wrap those methods. Having a wrapped interface like this around static members provide the testability.

OTHER TIPS

In ASP.NET MVC, HttpContextBase is designed to be mockable, so you can use its User property to get the current logged in user.

This will get you the logged in Username :

string userName = User.Identity.Name;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top