简体   繁体   English

具有异步ActionResult的Moq MVC控制器

[英]Moq mvc controller with async ActionResult

I am trying to moq this Controller action 我正在尝试取消此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();
        }

using this test method 使用这种测试方法

[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();
}

When I run the test I get this error "Invalid setup on a non-virtual (overridable in VB) member: x => x.Index(.testToConvert, .from, .to)"}" 运行测试时,出现此错误“在非虚拟(在VB中可重写)成员上的无效设置:x => x.Index(.testToConvert,.from,.to)“}”

any idea how to properly set up a moc for this. 任何想法如何为此适当地设置MOC。 I am trying to test the Tempdata["test"] existing and value. 我试图测试Tempdata [“ test”]的存在和价值。 Thank you 谢谢

UPDATE: All I needed to do is to test the Async ActionResult. 更新:我要做的只是测试异步ActionResult。 Here is the final unit test 这是最终的单元测试

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"]);

        }

The method Index needs to be declared virtual otherwise the mocking framework cannot intercept it. 需要将Index方法声明为virtual否则virtual框架无法对其进行拦截。 This is a common limitation of mocking frameworks that use Castle Dynamic Proxy . 这是使用Castle Dynamic Proxy的模拟框架的常见限制。 Rhino Mocks has the same problem, to get around it use dependency injection and pass objects around using interfaces as interfaces can always be mocked. Rhino Mocks也有同样的问题,要使用依赖注入来解决它并使用接口传递对象,因为总是可以模拟接口。

Is there an IHomeController ? IHomeController吗? Then you just need to change this line: 然后,您只需要更改此行:

var moq = new Mock<IHomeController>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM