Click here to Skip to main content
Click here to Skip to main content
Go to top

Unit Testing - No Time for Sleeping

, 22 Jun 2011
Rate this:
Please Sign up or sign in to vote.
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).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Andrew Rissing
Software Developer (Senior)
United States United States
Since I've begun my profession as a software developer, I've learned one important fact - change is inevitable. Requirements change, code changes, and life changes.
 
So..If you're not moving forward, you're moving backwards.

Comments and Discussions

 
GeneralReason for my vote of 5 Interesting! I am going to try it. T... PinmemberDrABELL23-Jun-11 3:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 22 Jun 2011
Article Copyright 2011 by Andrew Rissing
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid