多线程 – 单元测试异步方法的最好方法是什么?

栏目: 编程工具 · 发布时间: 6年前

内容简介:我似乎找不到一个.NET答案这个问题,我认为这将是相当普遍的.单元测试异步方法的最佳模式是什么?显然,我需要调用该方法,然后查看回调是否触发,但是有一种比简单的睡眠更好的方法,然后检查由回调设置的标志?管理标志在运行多个测试的地方有点乱.

我似乎找不到一个.NET答案这个问题,我认为这将是相当普遍的.

单元测试异步方法的最佳模式是什么?

显然,我需要调用该方法,然后查看回调是否触发,但是有一种比简单的睡眠更好的方法,然后检查由回调设置的标志?管理标志在运行多个测试的地方有点乱.

我通常使用匿名委托和一个waithandle. FOr示例我在我的演示者中有一个名为SetRemoteTableName的功能.当名称设置时,它也会引发一个事件.我想测试那个异步提出的事件.测试如下所示:
[TestMethod]
[WorkItem(244)]
[Description("Ensures calling SetRemoteTableName with a valid name works 
              AND raises the RemoteTableNameChange event")]
public void SetRemoteTableNamePositive()
{
  string expected = "TestRemoteTableName";
  string actual = string.Empty;

  AutoResetEvent are = new AutoResetEvent(false);
  SQLCECollectorPresenter presenter = new SQLCECollectorPresenter();
  presenter.RemoteTableNameChange += new EventHandler<GenericEventArg<string>>(
    delegate(object o, GenericEventArg<string> a)
    {
      actual = a.Value;
      are.Set();
    });

  presenter.SetRemoteTableName(expected);
  Assert.IsTrue(are.WaitOne(1000, false), "Event never fired");
  Assert.AreEqual(actual, expected);
}

http://stackoverflow.com/questions/400552/what-is-the-best-way-to-unit-test-an-asynchronous-method


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Learn Python the Hard Way

Learn Python the Hard Way

Zed Shaw / Example Product Manufacturer / 2011

This is a very beginner book for people who want to learn to code. If you can already code then the book will probably drive you insane. It's intended for people who have no coding chops to build up t......一起来看看 《Learn Python the Hard Way》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具