我正在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
的测试方法中出现错误。
如何解决此错误?
答案 0 :(得分:3)
[TestMethod]
public async Task Login_Test()
{
// Arrange
var logonModel = new LoginViewModel() { UserName = "Admin", Password = "admin123" };
// Validate model state start
var validationContext = new ValidationContext(logonModel, null, null);
//set validateAllProperties to true to validate all properties; if false, only required attributes are validated.
Validator.TryValidateObject(logonModel, validationContext, validationResults, true);
foreach (var validationResult in validationResults)
{
controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
}
// Validate model state end
// Act
var result = await controller.Login(logonModel, null) as RedirectToRouteResult;
// Assert
Assert.AreEqual("Index", result.RouteValues["action"]);
Assert.AreEqual("Home", result.RouteValues["controller"]);
}
这是我的问题的解决方案。它适用于异步方法。您必须将操作的返回类型更改为async Task
,然后调用方法后跟await
关键字。