2014-09-18 14 views
-1

我從AccountController.cs中獲得以下代碼,並且試圖(在我的mananger的指令中)針對驗證ModelState的一部分登錄函數運行單元測試。Visual Studio在測試代碼中調用異步函數時拋出一個錯誤

下面是函數:

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

注意函數如何使用新的「異步」的關鍵字與「任務」對象一起。

現在我已經安裝在我的測試是這樣的...

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

我覈實,引用是爲了(改變符號將「登錄」改爲「LoginTest」會導致錯誤,而我的測試代碼不會調用「LoginTest」)。我只是想知道有沒有人遇到過這個問題,也許可以告訴我我做錯了什麼。

在此先感謝。

回答

2

用異步裝飾測試方法或使用.Result對來自控制器的任務。

+0

這樣做了,謝謝! – 2014-09-18 21:44:42

相關問題