编程语言
首页 > 编程语言> > c# – 如何模拟会员提供者

c# – 如何模拟会员提供者

作者:互联网

我如何模拟我的会员提供者(我有自定义会员提供者,但不知道如何模拟它并将会员资格作为提供者提供为Membership.Provider只有getter)并在我的单元测试中使用该模拟的自定义成员资格提供者?

这是我的控制器

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");
        }
}

这是我的测试(使用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是对的,你不应该直接使用Membership类.我知道在某些情况下您需要使用Membership类,因此添加了以下信息.

您需要将Membership类包装在一个类中(从接口派生),然后您可以在需要的地方进行模拟.

削减我们所拥有的简短版本:

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);
        }
   }

在您的控制器中只需注入:

public class AdminController : Controller
{
    private readonly IMembershipService _membershipService;
    private readonly IEmailService _emailService;

    public AdminController(IMembershipService membershipService, 
        IEmailService emailService)
    {
        _membershipService = membershipService;
        _emailService = emailService;
    }
}

在单元测试中,您可以:

    var membershipService = new Mock<IMembershipService>();

标签:c,unit-testing,asp-net-mvc,moq,membership-provider
来源: https://codeday.me/bug/20190612/1223647.html