Visual Studio在测试代码中调用异步函数时抛出错误

时间:2014-09-18 21:08:21

标签: c# nunit async-await .net-4.5 fakeiteasy

我有来自AccountController.cs的以下代码,我正在尝试(根据我的mananger的指示)对验证ModelState的登录函数的一部分运行单元测试。

这是功能:

//
// 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);
        }
    }

注意该函数如何使用新的“async”关键字和“Task”对象。

现在我已经设置了我的测试......

[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()

    }

没关系,我还没有完成这个功能......我没有完成它的原因,是因为就在那里

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

我收到以下错误:

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'.

我已经验证了引用是有序的(将“Login”的签名更改为“LoginTest”会导致我的测试代码没有调用“LoginTest”时出错)。我只是想知道是否有人之前遇到过这个问题,也许可以告诉我我做错了什么。

提前致谢。

1 个答案:

答案 0 :(得分:2)

使用异步装饰测试方法或使用来自控制器的任务.Result。

相关问题