设置 UI 和后台任务计划,并在单元测试中用这个替换它们。
以下代码是从互联网复制的,很抱歉缺少对作者的引用:
public class CurrentThreadTaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task)
{
TryExecuteTask(task);
}
protected override bool TryExecuteTaskInline(
Task task,
bool taskWasPreviouslyQueued)
{
return TryExecuteTask(task);
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return Enumerable.Empty<Task>();
}
public override int MaximumConcurrencyLevel => 1;
}
所以要测试代码:
public TaskScheduler TaskScheduler
{
get { return taskScheduler ?? (taskScheduler = TaskScheduler.Current); }
set { taskScheduler = value; }
}
public TaskScheduler TaskSchedulerUI
{
get { return taskSchedulerUI ?? (taskSchedulerUI = TaskScheduler.FromCurrentSynchronizationContext()); }
set { taskSchedulerUI = value; }
}
public Task Update()
{
IsBusy = true;
return Task.Factory.StartNew( () =>
{
LongRunningTask( );
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler )
.ContinueWith( t => IsBusy = false, TaskSchedulerUI );
}
您将编写以下单元测试:
[Test]
public void WhenUpdateThenAttributeManagerUpdateShouldBeCalled()
{
taskScheduler = new CurrentThreadTaskScheduler();
viewModel.TaskScheduler = taskScheduler;
viewModel.TaskSchedulerUI = taskScheduler;
viewModel.Update();
dataManagerMock.Verify( s => s.UpdateData( It.IsAny<DataItem>>() ) );
}