【发布时间】:2014-09-08 06:18:45
【问题描述】:
我正在 MVC 5 中创建一个测试项目。
我遇到错误
Error 1 Cannot convert type 'System.Threading.Tasks.Task<System.Web.Mvc.ActionResult>' to 'System.Web.Mvc.ViewResult' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
这是我的代码:
[TestMethod]
public void LoginTest()
{
// Arrange
Mock<IAccountService<ApplicationUser>> membership = new Mock<IAccountService<ApplicationUser>>();
var logonModel = new LoginViewModel() { UserName = null, Password = null };
obj = new AccountController();
// Act
ViewResult result = obj.Login(logonModel,"") as ViewResult;
// Assert
Assert.AreEqual(result.ViewName, "Index");
Assert.IsFalse(obj.ModelState.IsValid);
Assert.AreEqual(obj.ModelState[""],"The user name or password provided is incorrect.");
}
我正在测试我的控制器操作
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await _accountService.FindAsync(model.UserName, model.Password);
if (user != null )
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return View(model);
}
编辑:我在这一行 obj.Login(loginviewmodel,"") as ViewResult 的测试方法中遇到错误,因为登录操作返回 Task<ActionResult> 类型,我将其转换为 ViewResult。
如何解决这个错误?
【问题讨论】:
-
它不起作用,因为我正在使用没有 async 关键字的 testmethod 测试
async方法。当我的 Login 方法返回Task时,我必须将我的测试方法的返回类型设置为Task后跟async关键字并使用 await 关键字调用该方法。它有效。 -
您能否使用您使用的代码以答案的形式提出您的解决方案?我遇到了同样的问题。
-
@BrendanHannemann 你可以查看我的答案
标签: c# asp.net-mvc unit-testing