Unit test controller

I want to create a Unit test for the following controller but it got fail in the Membership class:


    public class AccountController:BaseController
    {
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if(FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if(MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }
        public ActionResult LogOn()
        {
            return View("LogOn");
        }

        [HttpPost]
        public ActionResult LogOnFromUser(LappLogonModel model, string returnUrl)
        {
            if(ModelState.IsValid)
            {
                string UserName = Membership.GetUserNameByEmail(model.Email);
                if(MembershipService.ValidateUser(model.Email, model.Password))
                {
                    FormsService.SignIn(UserName, true);

                    var service = new AuthenticateServicePack();
                    service.Authenticate(model.Email, model.Password);
                    return RedirectToAction("Home");
                }
            }
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View("LogOn", model);
        }
    }

Unit test code:


    [TestClass]
    public class AccountControllerTest
    {
        [TestMethod]
        public void LogOnPostTest()
        {
            var mockRequest = MockRepository.GenerateMock();
            var target = new AccountController_Accessor();
            target.Initialize(mockRequest);
            var model = new LogonModel() { UserName = "test", Password = "1234" };
            string returnUrl = string.Empty;
            ActionResult expected = null;
            ActionResult actual = target.LogOn(model, returnUrl);
            if (actual == null)
                Assert.Fail("should have redirected");

        }
    }

When I googled, I got the following code but I don't know how to pass the membership to the accountcontroller


    var httpContext = MockRepository.GenerateMock();
                var httpRequest = MockRepository.GenerateMock();
                httpContext.Stub(x => x.Request).Return(httpRequest);
                httpRequest.Stub(x => x.HttpMethod).Return("POST");

                //create a mock MembershipProvider & set expectation
                var membershipProvider = MockRepository.GenerateMock();
                membershipProvider.Expect(x => x.ValidateUser(username, password)).Return(false);

                //create a stub IFormsAuthentication
                var formsAuth = MockRepository.GenerateStub();

            /*But what to do here???{...............
                ........................................
                ........................................}*/

                controller.LogOnFromUser(model, returnUrl);

Please help me to get this code working.


It appears as though you are using concrete instances of the IMembershipServive and IFormsAuthenticationService because you are using the Accessor to initialize them. When you use concrete classes you are not really testing this class in isolation, which explains the problems you are seeing.

What you really want to do is test the logic of the controller, not the functionalities of the other services.

Fortunately, it's an easy fix because the MembershipService and FormsService are public members of the controller and can be replaced with mock implementations.

// moq syntax:
var membershipMock = new Mock<IMembershipService>();
var formsMock = new Mock<IFormsAuthenticationService>();

target.FormsService = formsMock.Object;
target.MembershipService = membershipService.Object;

Now you can test several scenarios for your controller:

  • What happens when the MembershipService doesn't find the user?
  • The password is invalid?
  • The user and password is is valid?
  • Note that your AuthenticationServicePack is also going to cause problems if it has additional services or dependencies. You might want to consider moving that to a property of the controller or if it needs to be a single instance per authentication, consider using a factory or other service to encapsuate this logic.

    链接地址: http://www.djcxy.com/p/21410.html

    上一篇: 如何在C#中获取当前页面的URL

    下一篇: 单元测试控制器