0

我正在构建一个基于任务的服务器。我的问题是如何通过单元测试证明工作正常:

下面的方法是应用程序的核心,需要扎实。我需要它来执行任务链,如果启动它的日期在将来,则休眠等等。但是,当我使用 nuni gui 运行它时,它会永远挂起,并且使用http://www.testdriven.net/附加组件运行,并让它在后台运行,所以我无法阻止它VS IDE(即运行,然后根据IDE完成,但一直在后台运行,需要kill testdriven才能停止)

public Task RunPlan(plan thePlan)
{
    List<BackupTask> tasks = this.nextTasks(thePlan);
    List<Task> backupTasks = new List<Task>();

    TimeSpan wait;
    int i = 1;
    Task run = new Task(() =>
    {
        Logging.Debug("Starting {0}", thePlan);
    });
    //  Create a new token source
    var primaryTokenSource = new CancellationTokenSource();
    //  Create the cancellation token to pass into the Task
    CancellationToken token = primaryTokenSource.Token;

    workerTokens.GetOrAdd(run, primaryTokenSource);

    backupTasks.Add(run);

    foreach (var t in tasks)
    {
        BackupTask job = t;

        Task next = backupTasks.Last().ContinueWith(x =>
        {
            //  Check to see if we've been cancelled
            if (token.IsCancellationRequested)
            {
                Logging.Debug("Cancelled");
                return;
            }
            //Si es en el futuro, esperar
            wait = job.SuggestedDate - DateTime.Now;

            if (wait.TotalSeconds > 0)
            {
                Logging.Debug("Sleeping {0} secs..", wait.TotalSeconds);
                //http://stackoverflow.com/questions/1141617/thread-interrupt-to-stop-long-sleep-at-app-shutdown-is-there-a-better-approach
                //Thread.Sleep(TimeSpan.FromSeconds(wait.TotalSeconds));
                while (!stopping)
                {
                    lock (padlock)
                    {
                        Monitor.Wait(padlock, TimeSpan.FromSeconds(wait.TotalSeconds));
                    }
                }
            }

            //  Check to see if we've been cancelled
            if (token.IsCancellationRequested)
            {
                Logging.Debug("Cancelado");
                return;
            }

            job.doWork();
        },TaskContinuationOptions.LongRunning);
        backupTasks.Add(next);
    }

    backupTasks.First().Start();

    return backupTasks.Last();
}

和测试:

[Test]
public void testFullBackup()
{
    taskMgr.RunPlan(plans.First()).Wait();
    Assert.AreEqual(0, taskMgr.workerTokens.Count());
}
4

0 回答 0