【发布时间】:2014-04-04 03:38:17
【问题描述】:
我正在尝试最小化此控制器操作
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 => 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"]);
}
【问题讨论】:
-
你实际上想模拟什么,你想测试什么?如果您模拟
Index调用,您将不会对其进行测试... -
@john,我正在尝试最小化控制器并测试 Index 方法。
-
但是如果你在模拟控制器,你的 real 索引方法根本不会被调用......你只会调用模拟,它将返回您告诉它的任何内容。您需要模拟您尝试测试的代码的依赖项。 (所以在这种情况下,你可能会嘲笑你的助手。)
-
@John,你是 100% 正确的。我在深夜放了一个脑袋。只有我需要做的是测试控制器操作,而无需 Moq 任何东西。
标签: c# asp.net-mvc unit-testing asynchronous moq