Click here to Skip to main content
13,458,506 members
Click here to Skip to main content
Add your own
alternative version


1 bookmarked
Posted 22 Jun 2011

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))]


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).


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


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.

You may also be interested in...

Comments and Discussions

GeneralReason for my vote of 5 Interesting! I am going to try it. T... Pin
DrABELL23-Jun-11 3:01
memberDrABELL23-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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02-2016 | 2.8.180323.1 | Last Updated 22 Jun 2011
Article Copyright 2011 by Andrew Rissing
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid