gpt4 book ai didi

c# - 获取错误无法在单元测试中将类型 actionresult 转换为 viewresult

转载 作者:行者123 更新时间:2023-11-30 20:47:34 25 4
gpt4 key购买 nike

我正在 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.");
}

我正在测试的 Controller 操作如下

 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 .

如何解决这个错误?

最佳答案

    [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);
var validationResults = new List<ValidationResult>();

//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 关键字。

要使用验证方法,请为 System.ComponentModel.DataAnnotations 添加 using 语句

关于c# - 获取错误无法在单元测试中将类型 actionresult 转换为 viewresult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25718394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com