我正在考虑将某些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/