How can I mock my membership provider (I have custom membership provider, but don't know how to mock it and give to membership as provider as Membership.Provider has only getter) and use that mocked custom membership provider in my unit test?
Here is my controller
public class MyController
{
private IMyRepository myRepository;
public MyController(IMyRepository myRepository)
{
this.myRepository= myRepository;
}
[HttpGet]
public ActionResult Create()
{
var user = Membership.GetUser(); // <--- I want mock this method
ViewBag.User = user;
return View("Create");
}
}
And here is my test (using Moq)
[TestClass]
public class MyControllerUnitTest
{
private MyController controller;
public MyControllerUnitTest()
{
Mock<IMyRepository > myRepository = new Mock<IMyRepository>();
var controller = new GroupController(myRepository.Object);
}
[TestMethod]
public void TestMethod1()
{
var result = controller.Create() as ViewResult;
Assert.AreEqual("Create", result.ViewName);
}
}
@Sergey is right, you should not use Membership
class directly. I know you will need to user Membership class in some cases hence adding following information.
You need to wrap Membership
class in a class (derived from an interface) and then you can mock wherever required.
Cut short version of what we have got:
public interface IMembershipService
{
MembershipUser GetUserDetails(string emailAddress);
void CreateUserRole(string roleName);
void AssignUserToRole(string username, string roleName);
bool ValidateUserCredentials(string username, string password);
void SetAuthenticationCookie(string username, bool rememberMe);
void SignOut();
void UpdateUser(MembershipUser membershipUser);
bool DeleteUser(string username);
}
public class MembershipService : IMembershipService
{
public MembershipUser GetUserDetails(string emailAddress)
{
return Membership.GetUser(emailAddress);
}
public MembershipUser GetUserDetails(Guid membershipId)
{
return Membership.GetUser(membershipId);
}
}
In your controller just get it injected:
public class AdminController : Controller
{
private readonly IMembershipService _membershipService;
private readonly IEmailService _emailService;
public AdminController(IMembershipService membershipService,
IEmailService emailService)
{
_membershipService = membershipService;
_emailService = emailService;
}
}
In unit test you can do:
var membershipService = new Mock<IMembershipService>();
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