asp.net-mvc-2 - 为MVC2 AsyncController构建单元测试

标签 asp.net-mvc-2 asynccontroller

我正在考虑将某些MVC Controller 重写为异步 Controller 。我有针对这些 Controller 的工作单元测试,但是我试图了解如何在异步 Controller 环境中维护它们。

例如,当前我有一个类似这样的 Action :

public ContentResult Transaction()
{
    do stuff...
    return Content("result");
}

我的单元测试基本上看起来像:
var result = controller.Transaction();
Assert.AreEqual("result", result.Content);

好的,这很容易。

但是,当您的 Controller 更改为如下所示时:
public void TransactionAsync()
{
    do stuff...
    AsyncManager.Parameters["result"] = "result";
}

public ContentResult TransactionCompleted(string result)
{
    return Content(result);
}

您认为应该如何构建单元测试?您当然可以在测试方法中调用异步启动器方法,但是如何获得返回值?

我还没有在Google上看到任何有关此事的信息...

感谢您的任何想法。

最佳答案

与任何异步代码一样,单元测试需要了解线程信号。 .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
}

希望能有所帮助:)

关于asp.net-mvc-2 - 为MVC2 AsyncController构建单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2968892/

相关文章:

asp.net - 如何在 ASP.NET MVC 中使用 Html.Action() 将参数传递给 Action?

authentication - ASP.NET MVC2 应用程序中的第二层身份验证

c# - 异步操作完成,但结果未发送到浏览器

java - 使用tomcat和spring进行异步http请求处理

.net - 将我的思维方式从 ASP.NET 迁移到 ASP.NET MVC 时需要了解哪些关键概念 (2)?

json - mvc如何在不重定向到LogIn View 的情况下返回未经授权的代码

asp.net - ASP.NET MVC2中Ajax表单的错误重定向

c# - ASP.NET MVC2 从 jQuery 调用 AsyncController 方法?

C# Async MVC 方法返回 ContentResult System.Threading.Tasks.Task`1[System.Web.Mvc.JsonResult]