构建单元测试MVC2 AsyncControllers [英] Building unit tests for MVC2 AsyncControllers

查看:144
本文介绍了构建单元测试MVC2 AsyncControllers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在考虑重新改写我的一些MVC控制器是异步控制器。我有工作的单元测试这些控制器,但我想了解如何维护他们的异步控制器环境。

I'm considering re-rewriting some of my MVC controllers to be async controllers. I have working unit tests for these controllers, but I'm trying to understand how to maintain them in an async controller environment.

例如,目前我有一个这样的动作:

For example, currently I have an action like this:

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

和我的单元测试基本上是这样的:

and my unit test basically looks like:

var result = controller.Transaction();
Assert.AreEqual("result", result.Content);

好吧,这是很容易。

Ok, that's easy enough.

但是,当你的控制器更改如下:

But when your controller changes to look like this:

public void TransactionAsync()
{
    do stuff...
    AsyncManager.Parameters["result"] = "result";
}

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

你怎么想你的单元测试应该建?您当然可以调用异步方法引发在您的测试方法,但你怎么在返回值?

How do you suppose your unit tests should be built? You can of course invoke the async initiator method in your test method, but how do you get at the return value?

我还没有看到这个在谷歌什么...

I haven't seen anything about this on Google...

感谢您的任何想法。

推荐答案

对于任何异步code,单元测试需要知道线程的信令。 .NET包括称为的AutoResetEvent类型,它可以阻止在测试线程,直到一个异步操作已经完成:

As with any async code, unit testing needs to be aware of thread signalling. .NET includes a type called AutoResetEvent which can block the test thread until an async operation has been completed:

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
}

希望有所帮助:)

Hope that helps :)

这篇关于构建单元测试MVC2 AsyncControllers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆