【问题标题】:Wrapper around TASKs in C#C# 中的 TASK 封装
【发布时间】:2017-04-20 07:24:44
【问题描述】:

我正在使用 WinForms (.NET 4.0) 中的任务来执行冗长的操作,例如 WCF 调用。应用已经在大量使用Tasks的产品中(几乎所有使用Tasks的方法都是void)。

在单元测试期间,我们使用AutoResetEvents(在实际代码中)找出给定任务何时完成然后执行断言。

这让我想到几乎所有的AutoResetEvent 都是浪费精力。它们只是满足单元测试需求,没有别的。

我们是否可以在实际代码运行时同样围绕任务创建一个包装器...它们应该在后台工作,并且在单元测试的情况下它们应该是同步的。

类似于BackgroundWorker 的以下链接。

http://si-w.co.uk/blog/2009/09/11/unit-testing-code-that-uses-a-backgroundworker/

【问题讨论】:

  • 为什么不能在这些任务上使用Wait() 来查找它们何时完成?
  • 方法已经用 void 写回了很久。使用 Task 返回更新所有方法将是一项非常艰巨的任务。
  • 我以为您已经想更新方法以删除 AutoResetEvents 并引入 Task 包装器。我的建议还差多少?

标签: unit-testing asynchronous c#-4.0 task-parallel-library task


【解决方案1】:

为什么你不能简单地在你的包装器中使用任务的延续,像这样:

var task = ...
task.ContinueWith(t => check task results here)

另外,unit tests can be marked as async,如果他们有一个返回类型Task,那么你可以在那里使用await,然后做你的断言:

[Test]
public async Task SynchronizeTestWithRecurringOperationViaAwait()
{
    var sut = new SystemUnderTest();
    // Execute code to set up timer with 1 sec delay and interval.
    var firstNotification = sut.StartRecurring();
    // Wait that operation has finished two times.
    var secondNotification = await firstNotification.GetNext();
    await secondNotification.GetNext();
    // Assert outcome.
    Assert.AreEqual("Init Poll Poll", sut.Message);
}

另一种方法(来自同一篇文章)是使用自定义任务调度程序,在单元测试的情况下它将是同步的:

[Test]
public void TestCodeSynchronously()
{
    var dts = new DeterministicTaskScheduler();
    var sut = new SystemUnderTest(dts);
    // Execute code to schedule first operation and return immediately.
    sut.StartAsynchronousOperation();
    // Execute all operations on the current thread.
    dts.RunTasksUntilIdle();
    // Assert outcome of the two operations.
    Assert.AreEqual("Init Work1 Work2", sut.Message);
}

同一 MSDN 杂志包含不错的 article about best practices for async unit testing。此外,async void 应仅用作事件处理程序,所有其他方法应具有 async Task 签名。

【讨论】:

  • 就像我在问题中提到的...我使用的是 .NET 4.0,所以不能使用 async 和 await
  • @Abhash786 你可以使用Microsoft.Bcl.Async。虽然它确实需要 C# 5.0 编译器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-19
相关资源
最近更新 更多