Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a MembershipUser

I'm currently developing an asp.net mvc 2 application which uses the default SqlMembershipProvider for authentication. I've implemented a controller method that reads the ProviderUserKey of the current user by calling Membership.GetUser().ProviderUserKey. Now I'm trying to write some test methods for this controller.

To get rid of the dependancy on the static Membership class, I've created a thin wrapper and made my controller depend on the corresponding interface:

public interface IStaticMembershipService {
    MembershipUser GetUser();

    void UpdateUser(MembershipUser user);
}

So far everything works, but in order to unit-test the controller, I still need to mock the GetUser() method of this interface and return a MembershipUser object that contains a ProviderUserKey property. What is the easiest way to mock such an object?

I'm using moq as mocking framework.

like image 879
Simon Avatar asked Nov 23 '10 15:11

Simon


1 Answers

It'd look something like this:

var membershipMock = new Mock<IStaticMembershipService>();
var userMock = new Mock<MembershipUser>();
userMock.Setup(u => u.ProviderUserKey).Returns(guid);
membershipMock.Setup(s => s.GetUser()).Returns(userMock.Object);

If the MembershipUser class doesn't lend itself to mocking (i.e. if ProviderUserKey isn't virtual), you'll want to create your own object to represent the values you're going to need from a MembershipUser object, and have your service return one of those instead.

There's also a slight possibility that a MembershipUser is a poco-like object, and you can create an instance like this:

var userMock = new MembershipUser {ProviderUserKey = guid};
like image 97
StriplingWarrior Avatar answered Nov 15 '22 16:11

StriplingWarrior