I have a problem testing a logon method using existing AccountController (made by MVC)…
I have this simple test method:
[TestMethod]
public void LogOnTest1() {
AccountController controller = new AccountController();
LogOnModel logonModel = new LogOnModel();
logonModel.UserName = "test";
logonModel.Password = "test1234";
if ( controller.MembershipService == null ) {
controller.MembershipService = new AccountMembershipService();
}
if ( controller.FormsService == null ) {
controller.FormsService = new FormsAuthenticationService();
}
var result = controller.LogOn( logonModel, "" ) as ViewResult;
Assert.AreEqual( "Index", result.ViewName );
}
and the method defined in AccountController:
[HttpPost]
public ActionResult LogOn( LogOnModel model, string returnUrl ) {
if ( ModelState.IsValid ) {
if ( MembershipService.ValidateUser( model.UserName, model.Password ) ) {
FormsService.SignIn( model.UserName, model.RememberMe );
if ( !string.IsNullOrEmpty( returnUrl ) ) {
return Redirect( returnUrl );
} else {
return RedirectToAction( "Index", "Home" );
}
} else {
ModelState.AddModelError( "", "The user name or password provided is incorrect." );
}
}
// If we got this far, something failed, redisplay form
return View( model );
}
The above method is not defined/modified by me. Just created by when create an asp.net mvc project.
The problem is at line
if ( MembershipService.ValidateUser( model.UserName,model.Password ) ) {
which returns always false though I provided correct login info.
Where is my mistake ?
First of all, do not use
ifstatements and other conditional logic in your tests. Also do not use concrete classes in your tests. If this test will fail, how will you know why? What was broken – controller orAccountMembershipService? Use abstract dependencies, which could be mocked.And your tests:
Interesting here is that you don’t care which logon info you passed to controller. You mock response from membership service, which says logon was incorrect.
FEW TESTS MORE: