MVC Moq多个依赖项

时间:2016-03-22 21:34:53

标签: c# asp.net asp.net-mvc moq rhino-mocks

我正在ASP.NET MVC 4上开发一个应用程序。我正在使用TDD方法来开发我的应用程序。最初,我正在尝试为应用程序实现登录模块。从技术上讲,要登录,需要按照以下步骤操作:

  1. 验证用户帐户未锁定且是有效用户。 (如果用户尝试多次登录,则必须在5次尝试失败后锁定帐户。为实现此目的,我的数据库中有一个LoginAttempt字段,我在每次尝试失败后都会更新)
  2. 如果帐户已经过验证,请使用第三方服务使用loginId和密码验证用户。
  3. 如果已经过验证,则必须将用户重定向到“索引”页面。
  4. 为了完成这些任务,我创建了:

    // Interface, Controller will interact with    
    public Interface IAuthenticate
    {
        bool ValidateUser(string UserId,string Password);
    }
    
    // Class that implement IAuthenticate
    public class Authenticate : IAuthenticate
    { 
    
        private IVerifyUser loginVerify;
        private IThirdPartyService thirdpartyService;
    
        public Authenticate(IVerifyUser user,IThirdPartyService thirdparty)
        {    
            this.loginVerify=user;
            this.thirdpartyService=thirdparty;    
        }
    
        public bool ValidateUser(string userId,string password)
        {
            if(loginVerify.Verify(userId))
            {
                if(thirdpartyService.Validate(userId,password))
                    return true;
                else 
                    return false;    
            }
            else
                return false;
        }
    }
    

    要测试我的控制器登录,我是否必须为IAuthenticate创建模拟,或者我必须为IVerifyUserIThirdPartyService创建模拟?

     [TestMethod]
     public void Login_Rerturn_Error_If_UserId_Is_Incorrect()
     {
        Mock<IAuthenticate> mock1 = new Mock<IAuthenticate>();
    
        mock1.Setup(x => x.ValidateUser("UserIdTest", "PasswordTest"))
            .Returns(false);
    
        var results = controller.Login();
        var redirect = results as RedirectToRouteResult;
    
        Assert.IsNotNull(results);
        Assert.IsInstanceOfType(results, typeof(RedirectToRouteResult));
    
        controller.ViewData.ModelState.AssertErrorMessage("Provider", "User Id and Password is incorrect");
    
        Assert.AreEqual("Index", redirect.RouteValues["action"], "Wrong action");
    
        Assert.AreEqual("Home", redirect.RouteValues["controller"], "Wrong controller");
    }
    

1 个答案:

答案 0 :(得分:1)

如果您正在测试您的控制器并且您的控制器依赖于IAuthenticate的实例,那么您只需要模拟。通过嘲笑它,你无视其中的任何实际实现。您只是在使用IAuthenticate确定最终行为时测试控制器的行为。

在您的单元测试中,您将对IAuthenticate的实现进行测试,然后模拟其依赖项(IVerifyUserIThirdPartyService)来测试它的行为,给定它们的任何一个最终结果方法

如果您需要任何澄清,请发表评论! :)