我想在Asp.net中测试帐户控制器 帐户控制器是身份的一部分 是否需要测试帐户控制器?
答案 0 :(得分:2)
免责声明:我在Typemock工作。
在使用Typemock Isolator时,一般情况下测试ASP.net控制器和特别是帐户控制器也很容易。 以下是对帐户控制器的Login方法的测试示例:
测试方法(取自VS2015 MVC模板):
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
测试:
[TestMethod, Isolated]
public async Task TestWhenLoginIsBad_ErrorMessageIsShown()
{
// Arrange
// Create the wanted controller for testing
var controller = new AccountController();
var loginData = new LoginViewModel { Email = "support@typemock.com", Password = "password", RememberMe = false };
// Fake the ModelState
Isolate.WhenCalled(() => controller.ModelState.IsValid).WillReturn(true);
// Ignore AddModelError (should be called when login fails)
Isolate.WhenCalled(() => controller.ModelState.AddModelError("", "")).IgnoreCall();
// Fake HttpContext to return a fake ApplicationSignInManager
var fakeASIM = Isolate.WhenCalled(() => controller.HttpContext.GetOwinContext().Get<ApplicationSignInManager>()).ReturnRecursiveFake();
// When password checked it will fail. Note we are faking an async method
Isolate.WhenCalled(() => fakeASIM.PasswordSignInAsync(null, null, true, true)).WillReturn(Task.FromResult(SignInStatus.Failure));
// Act
var result = await controller.Login(loginData, "http://www.typemock.com/");
// Assert
// The result contains login data, doesn’t redirect
Assert.IsInstanceOfType(result, typeof(ViewResult));
Assert.AreSame(loginData, (result as ViewResult).Model);
// Make sure that the code added an error
Isolate.Verify.WasCalledWithExactArguments(() => controller.ModelState.AddModelError("", "Invalid login attempt."));
}
如果您想了解更多here,请参阅完整示例。
答案 1 :(得分:0)
对于一般的单元测试,您可以查看本文
有关帐户控制器的测试,请查看以下文章
http://blogs.interknowlogy.com/2014/08/21/mvc-series-part-2-accountcontroller-testing/
[Test]
public void ShouldNotAcceptInvalidUser()
{
// Arrange
Mock<IMembershipService> membership = new Mock<IMembershipService>();
membership.Setup(m => m.ValidateUser(It.IsAny<string>(), It.IsAny<string>()))
.Returns(false);
Mock<IFormsService> forms = new Mock<IFormsService>();
var logonModel = new LogOnModel() { UserName = "", Password = "" };
var controller = new AccountController(membership.Object, forms.Object);
// Act
var result = controller.LogOn(logonModel, "") as ViewResult;
// Assert
Assert.That(result.ViewName, Is.EqualTo("Index"));
Assert.False(controller.ModelState.IsValid);
Assert.That(controller.ModelState[""],
Is.EqualTo("The user name or password provided is incorrect."));}