我正在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

如何解决这个错误?

最佳答案

    [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/

10-13 05:53