Click here to Skip to main content
15,879,082 members
Articles / DevOps / Testing
Tip/Trick

Unit Testing - No Time for Sleeping

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
22 Jun 2011CPOL 19K   1   1
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)


Written By
Architect
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... Pin
DrABELL23-Jun-11 3:01
DrABELL23-Jun-11 3:01 

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

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