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

这是我的 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");
        }
}

这是我的测试(使用 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 类包装在一个类中(从接口(interface)派生),然后您可以在任何需要的地方进行模拟。

剪切我们所拥有的简短版本:

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

在你的 Controller 中注入(inject)它:
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# - 如何模拟成员(member)提供者,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28010282/

10-08 21:38