【问题标题】:Visual Studio throwing an error on called async function from test codeVisual Studio 在测试代码中调用的异步函数上抛出错误
【发布时间】:2014-09-19 05:21:09
【问题描述】:

我有来自 AccountController.cs 的以下代码,我正在尝试(按照我的经理的指示)对验证 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”时出错)。我只是想知道是否有人以前遇到过这个问题,也许可以告诉我我做错了什么。

提前致谢。

【问题讨论】:

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


    【解决方案1】:

    使用 async 装饰测试方法或在控制器的任务上使用 .Result。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多