How To Test AccountController In ASP?

本文关键字:ASP In AccountController To Test How | 更新日期: 2023-09-27 17:57:41

我想在Asp.net中测试帐户控制器帐户管理员是身份的一部分有必要测试账户管理员吗?

How To Test AccountController In ASP?

免责声明:我在Typemock工作。

当使用Typemock Isolator时,测试ASP.net控制器是可能的,也很容易。下面是一个测试帐户控制器登录方法的例子:

测试中的方法(取自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."));
}

如果你想了解更多,这里是完整的例子。

对于一般的单元测试,您可以查看本文

http://www.asp.net/mvc/overview/older-versions-1/unit-testing/creating-unit-tests-for-asp-net-mvc-applications-cs

对于帐户控制器的测试,请查看以下文章

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."));}