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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With