具有异步ActionResult的Moq mvc控制器

时间:2014-03-03 07:19:59

标签: c# asp.net-mvc unit-testing asynchronous moq

我正在尝试moq这个Controller动作

public async Task<ActionResult> Index(decimal total, string from, string to)
        {

            decimal result = 0.00m;
            await Helper.GetEmployeeSalaryAsync(total, fromCurrency, toCurrency ,ConvertedValue =>
            {
                result = ConvertedValue;
                TempData["ConvertedResult"] = result;

            }).ConfigureAwait(false);

            return View();
        }

使用此测试方法

[TestMethod]
public void  Index_Should_Return_View_With_Converted_Currency()
{
    ActionResult resultView = null;
    decimal testToConvert = 110.00m;
    string from = "Home";
    string to = "Remote";


    var moq = new Mock<HomeController>();

    moq.Setup(x => x.Index(testToConvert, from, to))
        .ReturnsAsync(resultView)
        .Verifiable();
}

当我运行测试时,我收到此错误“非虚拟(在VB中可覆盖)成员的无效设置:x =&gt; x.Index(.testToConvert,.from,.to)”}“

任何想法如何为此正确设置moc。我正在尝试测试Tempdata [“test”]的存在和价值。 谢谢

更新: 我需要做的就是测试Async ActionResult。这是最后的单元测试

public async Task  Index_Should_Return_View_With_Converted_Currency()
        {

            decimal testToConvert = 110.00m;

            string from = "Home";
            string to = "Remote";
            HomeController controller = new HomeController();
         var  result = (ViewResult)  await controller.Index(testToConvert, from, to) ;

            Assert.IsNotNull(result.TempData["ConvertedResult"]);

        }

1 个答案:

答案 0 :(得分:1)

方法Index需要声明virtual,否则模拟框架无法拦截它。这是使用Castle Dynamic Proxy的模拟框架的常见限制。 Rhino Mocks有同样的问题,绕过它使用依赖注入并使用接口传递对象,因为接口总是可以被模拟。

IHomeController吗?然后你只需要改变这一行:

var moq = new Mock<IHomeController>();