Chr*_*isW 10 asynccontroller asp.net-mvc-2
我正在考虑重新编写一些我的MVC控制器作为异步控制器.我有这些控制器的工作单元测试,但我试图了解如何在异步控制器环境中维护它们.
例如,目前我有这样的动作:
public ContentResult Transaction()
{
    do stuff...
    return Content("result");
}
我的单元测试基本上看起来像:
var result = controller.Transaction();
Assert.AreEqual("result", result.Content);
好的,这很容易.
但是,当您的控制器更改为如下所示:
public void TransactionAsync()
{
    do stuff...
    AsyncManager.Parameters["result"] = "result";
}
public ContentResult TransactionCompleted(string result)
{
    return Content(result);
}
您如何构建单元测试?您当然可以在测试方法中调用异步启动器方法,但是如何获得返回值?
我在Google上没有看到任何相关内容......
谢谢你的任何想法.
Mat*_*ott 18
与任何异步代码一样,单元测试需要了解线程信令..NET包含一个名为AutoResetEvent的类型,它可以阻止测试线程,直到异步操作完成:
public class MyAsyncController : Controller
{
  public void TransactionAsync()
  {
    AsyncManager.Parameters["result"] = "result";
  }
  public ContentResult TransactionCompleted(string result)
  {
    return Content(result);
  }
}
[TestFixture]
public class MyAsyncControllerTests
{
  #region Fields
  private AutoResetEvent trigger;
  private MyAsyncController controller;
  #endregion
  #region Tests
  [Test]
  public void TestTransactionAsync()
  {
    controller = new MyAsyncController();
    trigger = new AutoResetEvent(false);
    // When the async manager has finished processing an async operation, trigger our AutoResetEvent to proceed.
    controller.AsyncManager.Finished += (sender, ev) => trigger.Set();
    controller.TransactionAsync();
    trigger.WaitOne()
    // Continue with asserts
  }
  #endregion
}
希望有帮助:)
| 归档时间: | 
 | 
| 查看次数: | 1429 次 | 
| 最近记录: |