如何编写单元测试与第三方物流和的TaskScheduler [英] How to write unit tests with TPL and TaskScheduler

查看:151
本文介绍了如何编写单元测试与第三方物流和的TaskScheduler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下这样的函数:

private static ConcurrentList<object> list = new ConcurrentList<object>();
public void Add(object x)
{
   Task.Factory.StartNew(() =>
   {
      list.Add(x); 
   }
}

我不关心何时完全fentry被添加到列表中,但我需要它在结尾处添加(明显;))

I don't care WHEN exactly the fentry is added to the list, but i need it to be added in the end ( obviously ;) )

我不明白的方式妥善单元测试这样的东西不返回任何回调处理程序或某事。而这并不需要为程序添加为此逻辑

I don't see a way to properly unittest stuff like this without returning any callback-handler or sth. and therefor adding logic that's not required for the program

你会怎么做呢?

推荐答案

一个做到这一点的方法是使你的类型配置,使得它需要一个的TaskScheduler 实例。

One way to do this is to make your type configurable such that it takes a TaskScheduler instance.

public MyCollection(TaskScheduler scheduler) {
  this.taskFactory = new TaskFactory(scheduler);
}

public void Add(object x) {
  taskFactory.StartNew(() => {
    list.Add(x);
  });
}

现在在单元测试中,你可以做的是创建的TaskScheduler 的可测试版本。这是被设计为可配置的抽象类。简单有时间表功能添加项目到一个队列,然后添加一个函数来手动完成所有队列中的现在。然后,你的单元测试可以像这样

Now in your unit tests what you can do is create a testable version of TaskScheduler. This is an abstract class which is designed to be configurable. Simple have the schedule function add the items into a queue and then add a function to manually do all of the queue items "now". Then your unit test can look like this

var scheduler = new TestableScheduler();
var collection = new MyCollection(scehduler);
collection.Add(42);
scheduler.RunAll();
Assert.IsTrue(collection.Contains(42));

实施例 TestableScehduler

class TestableScheduler : TaskScheduler {
  private Queue<Task> m_taskQueue = new Queue<Task>();

  protected override IEnumerable<Task> GetScheduledTasks() {
    return m_taskQueue;
  }

  protected override void QueueTask(Task task) {
    m_taskQueue.Enqueue(task);
  }

  protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) {
    task.RunSynchronously();
  }

  public void RunAll() {
    while (m_taskQueue.Count > 0) {
      m_taskQueue.Dequeue().RunSynchronously();
    }
  }
}

这篇关于如何编写单元测试与第三方物流和的TaskScheduler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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