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.

有帮助吗?

解决方案

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.

其他提示

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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top