我正在构建一个基于任务的服务器。我的问题是如何证明单元测试是正确的:
以下方法是应用程序的核心,需要扎实。我需要它来执行任务链,如果将来启动它的日期就会睡觉,等等。然而,当我使用nuni gui运行它时,它会永远挂断,并且使用http://www.testdriven.net/附加组件运行,并让它在后台运行,所以我无法阻止它从VS IDE(即,运行,然后根据IDE完成,但继续在后台运行,需要杀死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());
}