单元测试控制器 - 成员错误

时间:2011-10-01 21:29:49

标签: asp.net asp.net-mvc unit-testing

我想为以下控制器创建一个单元测试,但它在Membership类中失败了:


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

单元测试代码:


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

        }
    }

当我用Google搜索时,我得到以下代码,但我不知道如何将会员资格传递给帐户控制器


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

请帮助我让这段代码正常工作。

1 个答案:

答案 0 :(得分:1)

好像您正在使用IMembershipServive和IFormsAuthenticationService的具体实例,因为您正在使用Accessor来初始化它们。当你使用具体的类时,你并没有真正独立地测试这个类,这解释了你所看到的问题。

您真正想要做的是测试控制器的逻辑,而不是其他服务的功能。

幸运的是,这是一个简单的修复,因为MembershipService和FormsService是控制器的公共成员,可以用模拟实现替换。

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

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

现在,您可以为控制器测试多种方案:

  • 当MembershipService找不到用户时会发生什么?
  • 密码无效?
  • 用户和密码有效吗?

请注意,如果AuthenticationServicePack具有其他服务或依赖项,也会导致问题。您可能需要考虑将其移动到控制器的属性,或者如果每个身份验证需要一个实例,请考虑使用工厂或其他服务来封装此逻辑。

豫ICP备18024241号-1