我正在ASP.NET MVC 4上开发一个应用程序。我正在使用TDD方法来开发我的应用程序。最初,我正在尝试为应用程序实现登录模块。从技术上讲,要登录,需要按照以下步骤操作:
LoginAttempt
字段,我在每次尝试失败后都会更新)为了完成这些任务,我创建了:
// 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
创建模拟,或者我必须为IVerifyUser
和IThirdPartyService
创建模拟?
[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");
}
答案 0 :(得分:1)
如果您正在测试您的控制器并且您的控制器依赖于IAuthenticate
的实例,那么您只需要模拟。通过嘲笑它,你无视其中的任何实际实现。您只是在使用IAuthenticate
确定最终行为时测试控制器的行为。
在您的单元测试中,您将对IAuthenticate
的实现进行测试,然后模拟其依赖项(IVerifyUser
和IThirdPartyService
)来测试它的行为,给定它们的任何一个最终结果方法
如果您需要任何澄清,请发表评论! :)