如何为表单验证的帐户控制器编写测试

发布于 2024-08-27 18:45:32 字数 5482 浏览 4 评论 0原文

试图弄清楚如何充分测试我的帐户控制器。我在测试成功登录场景时遇到问题。

问题 1)我是否缺少任何其他测试。(我正在单独测试模型验证属性)

问题 2)Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven() 和 Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven() 测试未通过。我已将范围缩小到我调用 _membership.validateuser() 的行。即使在我的服务模拟设置过程中,我声明每当调用 validateuser 时我都希望返回 true,但该方法调用返回 false。

这是到目前为止我得到的

AccountController.cs

[HandleError]
public class AccountController : Controller
{
    private IMembershipService _membershipService;

    public AccountController()
        : this(null)
    {
    }

    public AccountController(IMembershipService membershipService)
    {
        _membershipService = membershipService ?? new AccountMembershipService();
    }

    [HttpGet]
    public ActionResult LogOn()
    {
        return View();
    }

    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (_membershipService.ValidateUser(model.UserName,model.Password))
            {
                if (!String.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                return RedirectToAction("Index", "Overview");
            }
            ModelState.AddModelError("*", "The user name or password provided is incorrect.");
        }

        return View(model);
    }

}

AccountServices.cs

public interface IMembershipService
{
    bool ValidateUser(string userName, string password);
}

public class AccountMembershipService : IMembershipService
{
    public bool ValidateUser(string userName, string password)
    {
        throw new System.NotImplementedException();
    }
}

AccountControllerFacts.cs

public class AccountControllerFacts
{
    public static AccountController GetAccountControllerForLogonSuccess()
    {
        var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>();
        var controller = new AccountController(membershipServiceStub);
        membershipServiceStub
               .Stub(x => x.ValidateUser("someuser", "somepass"))
               .Return(true);
        return controller;
    }

    public static AccountController GetAccountControllerForLogonFailure()
    {
        var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>();
        var controller = new AccountController(membershipServiceStub);
        membershipServiceStub
               .Stub(x => x.ValidateUser("someuser", "somepass"))
               .Return(false);
        return controller;
    }

    public class LogOn
    {
        [Fact]
        public void Get_ReturnsViewResultWithDefaultViewName()
        {
            // Arrange
            var controller = GetAccountControllerForLogonSuccess();

            // Act
            var result = controller.LogOn();

            // Assert
            Assert.IsType<ViewResult>(result);
            Assert.Empty(((ViewResult)result).ViewName);
        }

        [Fact]
        public void Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven()
        {
            // Arrange
            var controller = GetAccountControllerForLogonSuccess();
            var user = new LogOnModel();

            // Act
            var result = controller.LogOn(user, null);
            var redirectresult = (RedirectToRouteResult) result;

            // Assert
            Assert.IsType<RedirectToRouteResult>(result);
            Assert.Equal("Overview", redirectresult.RouteValues["controller"]);
            Assert.Equal("Index", redirectresult.RouteValues["action"]);
        }

        [Fact]
        public void Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven()
        {
            // Arrange
            var controller = GetAccountControllerForLogonSuccess();
            var user = new LogOnModel();

            // Act
            var result = controller.LogOn(user, "someurl");
            var redirectResult = (RedirectResult) result;

            // Assert
            Assert.IsType<RedirectResult>(result);
            Assert.Equal("someurl", redirectResult.Url);
        }

        [Fact]
        public void Put_ReturnsViewIfInvalidModelState()
        {
            // Arrange
            var controller = GetAccountControllerForLogonFailure();
            var user = new LogOnModel();
            controller.ModelState.AddModelError("*","Invalid model state.");

            // Act
            var result = controller.LogOn(user, "someurl");
            var viewResult = (ViewResult) result;

            // Assert
            Assert.IsType<ViewResult>(result);
            Assert.Empty(viewResult.ViewName);
            Assert.Same(user,viewResult.ViewData.Model);
        }

        [Fact]
        public void Put_ReturnsViewIfLogonFailed()
        {
            // Arrange

            var controller = GetAccountControllerForLogonFailure();
            var user = new LogOnModel();

            // Act
            var result = controller.LogOn(user, "someurl");
            var viewResult = (ViewResult) result;

            // Assert
            Assert.IsType<ViewResult>(result);
            Assert.Empty(viewResult.ViewName);
            Assert.Same(user,viewResult.ViewData.Model);
            Assert.Equal(false,viewResult.ViewData.ModelState.IsValid);
        }
    }
}

Trying to figure out how to adequately test my accounts controller. I am having problem testing the successful logon scenario.

Issue 1) Am I missing any other tests.(I am testing the model validation attributes separately)

Issue 2) Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven() and Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven() test are not passing. I have narrowed it down to the line where i am calling _membership.validateuser(). Even though during my mock setup of the service i am stating that i want to return true whenever validateuser is called, the method call returns false.

Here is what I have gotten so far

AccountController.cs

[HandleError]
public class AccountController : Controller
{
    private IMembershipService _membershipService;

    public AccountController()
        : this(null)
    {
    }

    public AccountController(IMembershipService membershipService)
    {
        _membershipService = membershipService ?? new AccountMembershipService();
    }

    [HttpGet]
    public ActionResult LogOn()
    {
        return View();
    }

    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (_membershipService.ValidateUser(model.UserName,model.Password))
            {
                if (!String.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                return RedirectToAction("Index", "Overview");
            }
            ModelState.AddModelError("*", "The user name or password provided is incorrect.");
        }

        return View(model);
    }

}

AccountServices.cs

public interface IMembershipService
{
    bool ValidateUser(string userName, string password);
}

public class AccountMembershipService : IMembershipService
{
    public bool ValidateUser(string userName, string password)
    {
        throw new System.NotImplementedException();
    }
}

AccountControllerFacts.cs

public class AccountControllerFacts
{
    public static AccountController GetAccountControllerForLogonSuccess()
    {
        var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>();
        var controller = new AccountController(membershipServiceStub);
        membershipServiceStub
               .Stub(x => x.ValidateUser("someuser", "somepass"))
               .Return(true);
        return controller;
    }

    public static AccountController GetAccountControllerForLogonFailure()
    {
        var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>();
        var controller = new AccountController(membershipServiceStub);
        membershipServiceStub
               .Stub(x => x.ValidateUser("someuser", "somepass"))
               .Return(false);
        return controller;
    }

    public class LogOn
    {
        [Fact]
        public void Get_ReturnsViewResultWithDefaultViewName()
        {
            // Arrange
            var controller = GetAccountControllerForLogonSuccess();

            // Act
            var result = controller.LogOn();

            // Assert
            Assert.IsType<ViewResult>(result);
            Assert.Empty(((ViewResult)result).ViewName);
        }

        [Fact]
        public void Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven()
        {
            // Arrange
            var controller = GetAccountControllerForLogonSuccess();
            var user = new LogOnModel();

            // Act
            var result = controller.LogOn(user, null);
            var redirectresult = (RedirectToRouteResult) result;

            // Assert
            Assert.IsType<RedirectToRouteResult>(result);
            Assert.Equal("Overview", redirectresult.RouteValues["controller"]);
            Assert.Equal("Index", redirectresult.RouteValues["action"]);
        }

        [Fact]
        public void Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven()
        {
            // Arrange
            var controller = GetAccountControllerForLogonSuccess();
            var user = new LogOnModel();

            // Act
            var result = controller.LogOn(user, "someurl");
            var redirectResult = (RedirectResult) result;

            // Assert
            Assert.IsType<RedirectResult>(result);
            Assert.Equal("someurl", redirectResult.Url);
        }

        [Fact]
        public void Put_ReturnsViewIfInvalidModelState()
        {
            // Arrange
            var controller = GetAccountControllerForLogonFailure();
            var user = new LogOnModel();
            controller.ModelState.AddModelError("*","Invalid model state.");

            // Act
            var result = controller.LogOn(user, "someurl");
            var viewResult = (ViewResult) result;

            // Assert
            Assert.IsType<ViewResult>(result);
            Assert.Empty(viewResult.ViewName);
            Assert.Same(user,viewResult.ViewData.Model);
        }

        [Fact]
        public void Put_ReturnsViewIfLogonFailed()
        {
            // Arrange

            var controller = GetAccountControllerForLogonFailure();
            var user = new LogOnModel();

            // Act
            var result = controller.LogOn(user, "someurl");
            var viewResult = (ViewResult) result;

            // Assert
            Assert.IsType<ViewResult>(result);
            Assert.Empty(viewResult.ViewName);
            Assert.Same(user,viewResult.ViewData.Model);
            Assert.Equal(false,viewResult.ViewData.ModelState.IsValid);
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

您的好友蓝忘机已上羡 2024-09-03 18:45:32

弄清楚如何修复我的测试。

        [Fact]
        public void Put_ReturnsRedirectToRouteResultForOverviewIfLogonSuccessAndNoReturnUrlGiven()
        {
            // Arrange
            var mocks = new MockRepository();
            var mockMembershipService = mocks.StrictMock<IMembershipService>();
            using (mocks.Record())
            {
                Expect.Call(mockMembershipService.ValidateUser("", "")).IgnoreArguments().Return(true).Repeat.Any();
            }
            var controller = new AccountController(mockMembershipService);
            var user = new LogOnModel();

            // Act
            ActionResult result;
            using (mocks.Playback()){
                result = controller.LogOn(user, null);
            }

        // Assert
            Assert.IsType<RedirectToRouteResult>(result);
            var redirectresult = (RedirectToRouteResult)result;
            Assert.Equal("Overview", redirectresult.RouteValues["controller"]);
            Assert.Equal("Index", redirectresult.RouteValues["action"]);
        }

Figured out how to fix my tests.

        [Fact]
        public void Put_ReturnsRedirectToRouteResultForOverviewIfLogonSuccessAndNoReturnUrlGiven()
        {
            // Arrange
            var mocks = new MockRepository();
            var mockMembershipService = mocks.StrictMock<IMembershipService>();
            using (mocks.Record())
            {
                Expect.Call(mockMembershipService.ValidateUser("", "")).IgnoreArguments().Return(true).Repeat.Any();
            }
            var controller = new AccountController(mockMembershipService);
            var user = new LogOnModel();

            // Act
            ActionResult result;
            using (mocks.Playback()){
                result = controller.LogOn(user, null);
            }

        // Assert
            Assert.IsType<RedirectToRouteResult>(result);
            var redirectresult = (RedirectToRouteResult)result;
            Assert.Equal("Overview", redirectresult.RouteValues["controller"]);
            Assert.Equal("Index", redirectresult.RouteValues["action"]);
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文