-1

I have the following code from AccountController.cs and I am attempting (at my mananger's instruction) to run a unit test against a portion of the login function that validates the ModelState.

Here is the function:

//
// POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        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);
        }
    }

Notice how the function uses the new "async" keyword along with the "Task" object.

Now I have setup my test like so...

[Test]
    public void Account_ModelStateNotValid_ReturnsCorrectView()
    {
        //Arrange
        AccountController ac = A.Fake<AccountController>();
        LoginViewModel model = A.Fake<LoginViewModel>();


        //Act
        var result = await ac.Login(model, null);
        A.CallTo(() => ac.ModelState.IsValid).Returns(false);

        //Assert
        // Assert.That()

    }

Nevermind that I haven't completed the function... the reason I haven't completed it, is because right there at

var result = await ac.Login(model, null);

I get the following error:

Error 31 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

I have verified that references are in order (changing the signature of "Login" to "LoginTest" causes an error with my test code not calling "LoginTest"). I'm just wondering if anyone has come across this problem before, and perhaps can tell me what I'm doing wrong.

Thanks in advance.

Highspeed
  • 442
  • 3
  • 18

1 Answers1

2

Decorate the test metod with async or use .Result on the task from the controller.

Per
  • 1,061
  • 7
  • 11