Created
December 20, 2013 20:04
-
-
Save codereflection/8060574 to your computer and use it in GitHub Desktop.
Getting unit tests to run under a single thread. Just inherit the WithASingleThreadRestriction class from your unit tests and they'll run under a single thread making unit testing much easier.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
using System.Threading.Tasks; | |
namespace Tests | |
{ | |
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>(); | |
} | |
/// <summary> | |
/// Replaces the current task scheduler with an instance of the CurrentThreadTaskScheduler | |
/// using reflection. | |
/// </summary> | |
public void Start() | |
{ | |
var taskSchedulerType = typeof (TaskScheduler); | |
var defaultTaskSchedulerField = taskSchedulerType.GetField("s_defaultTaskScheduler", BindingFlags.SetField | BindingFlags.Static | BindingFlags.NonPublic); | |
if (defaultTaskSchedulerField != null) defaultTaskSchedulerField.SetValue(null, this); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Tests | |
{ | |
public class WithASingleThreadRestriction | |
{ | |
public WithASingleThreadRestriction() | |
{ | |
var currentThreadTaskScheduler = new CurrentThreadTaskScheduler(); | |
currentThreadTaskScheduler.Start(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment