Unit Testing - No Time for Sleeping





5.00/5 (2 votes)
A simple trick to remove the delay of Thread.Sleep for unit testing.
Using Moles .NET[^], you can quickly reduce the time to execute unit tests by rerouting calls to
Thread.Sleep
to be a no-op in your production code.
Note: In certain integration situations, Thread.Sleep
would be required, but I'm referring to artificial delays that may be injected for various reasons that are not necessary for unit testing.
The code would simply look like the following:
using System.Threading; using System.Threading.Moles; using Microsoft.Moles.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting; [assembly: MoledType(typeof(Thread))] ... [TestMethod] [HostType("Moles")] public void TestMethod1() { MThread.SleepInt32 = x => { /* Do nothing. */ }; /* Insert your normal unit test code here... */ }For cases where you need to circumvent the above, you can take advantage of
MolesContext.ExecuteWithoutMoles
or just clear out the Action you supplied to MThread.SleepInt32
.
Note: The above code will impact not only Thread.Sleep(int)
, but also Thread.Sleep(TimeSpan)
.