单元测试控制器

我想为以下控制器创建一个单元测试,但它在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时,我得到了下面的代码,但我不知道如何将成员资格传递给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);

请帮助我获得此代码的工作。


看起来好像您正在使用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具有其他服务或依赖关系,它也会导致问题。 您可能需要考虑将其转换为控制器的属性,或者如果需要对每个身份验证使用单个实例,请考虑使用工厂或其他服务来封装此逻辑。

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

    上一篇: Unit test controller

    下一篇: What is Unit test, Integration Test, Smoke test, Regression Test?