Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnitTest ASP.NET Application that Requires User to be Logged in

I've got an ASP.NET application that allows users to log on. Another part of my application uses the UserId (the user must be logged on to access the controller). How do I fake a logon for unit testing?

Here's how I get the UserId

Private _UserId As Guid
    Public ReadOnly Property UserId() As Guid
        Get
            _UserId = System.Web.Security.Membership.GetUser().ProviderUserKey
            Return _UserId
        End Get
    End Property

Thanks

EDIT

This is an MVC 3 project.

like image 237
Tyler DeWitt Avatar asked Nov 22 '11 22:11

Tyler DeWitt


1 Answers

You can write a wrapper class for your membership so you can create a Mock to use in your unit tests. code is in C#, i apologize but you'll get my point.

    public interface IMyMemberShip
    {
        Guid GetUserId();
    }

    public class MyMemberShip : IMyMemberShip
    {
        public Guid GetUserId()
        {
            return (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
        }
    }

    public class MockMyMembership : IMyMemberShip
    {
        public Guid GetUserId()
        {
            return Guid.NewGuid();
        }
    }

    public class AnotherPartOfYourApplication
    {
        IMyMemberShip _myMembership;

        public AnotherPartOfYourApplication(IMyMemberShip myMemberShip)
        {
            _myMembership = myMemberShip;
        }

        public void GetUserIdAndDoSomething()
        {
            var userId = _myMembership.GetUserId();
        }
    }

If you are not doing complex stuff in your mock though, i would probably use moq so you don't need a mock class at all in your unit tests.

var mock = new Mock<IMyMemberShip>();
mock.Setup(m => m.GetUserId()).Returns(Guid.NewGuid());
like image 79
zero7 Avatar answered Sep 26 '22 08:09

zero7