---
title: "Multi Threaded Unit Tests with Osherove.ThreadTester"
url: "https://osherove.com/blog/2007/6/22/multi-threaded-unit-tests-with-osherovethreadtester.md"
canonical: "https://osherove.com/blog/2007/6/22/multi-threaded-unit-tests-with-osherovethreadtester.html"
published: "2007-06-22T09:28:55"
updated: "2007-06-22T09:28:55"
tags: ["Agile", "Art Of Unit Testing", "General Software Devel..."]
author: "Roy Osherove"
description: "The title says \"unit tests\" but they are really integration tests, since we rely on the cpu and the context switching mechanisms of the OS to do the work for us, but still ,this tries to solve a scenario many people…"
usage: "Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page)."
license: "https://creativecommons.org/licenses/by/4.0/"
---

# Multi Threaded Unit Tests with Osherove.ThreadTester

By Roy Osherove June 22, 2007 In [Agile](https://osherove.com/blog/category/agile), [Art Of Unit Testing](https://osherove.com/blog/category/art-of-unit-testing), [General Software Devel...](https://osherove.com/blog/category/general-software-devel)

**Historical article** · Originally published June 22, 2007; technical details may be outdated.

The title says "unit tests" but they are really integration tests, since we rely on the cpu and the context switching mechanisms of the OS to do the work for us, but still ,this tries to solve a scenario many people have been asking me about.

The ThreadTester library helps create tests that use multiple threads. It’s main use is to synchronize and “block” the running test until all the threads have finished their job, or a timeout has occurred. It is designed to make the test developer's life easier with a simple API that is readable and quick to use. It's part of the code I'm developing for [my upcoming book](http://the.artofunittesting.com/).

**Download:**

[Binaries in zip file](http://files.osherove.com/downloads/Osherove.ThreadTester.zip)

[Source code in zip file](http://files.osherove.com/downloads/ThreadTester.src.zip)

Source code from svn repository(one of several test libraries there I created):

[http://tools.assembla.com/svn/NTestEx](http://tools.assembla.com/svn/NTestEx)

Here is the basic usage of this class:

1) add a reference to Osherove.threadtester into your test project.

2) Write a test that looks like this:

```
[Test]
        public void TwoThreads()
        {
            Counter c = new Counter();
            ThreadTester tt = new ThreadTester();
            tt.AddThreadAction(
                delegate
                    {
                        for (int i = 0; i < 100; i++)
                        {
                            c.Increment();
                            Thread.Sleep(15);
                        }
                    });

            
            tt.AddThreadAction(
                delegate
                    {
                        for (int i = 0; i < 100; i++)
                        {
                            c.Increment();
                            Thread.Sleep(100);
                        }
                    });

            tt.StartAllThreads(22500);
        }
```

the test above starts two threads and will block until both of them finish their job. The Counter class is a simple class that we'd like to test that only has a count property and an increment method. We want to make sure it is thread safe.

Here's a test that starts up 100 threads against counter:

```
        [Test]
        public void HundredThreads()
        {
            Counter c = new Counter();
            ThreadTester tt = new ThreadTester();
            for (int i = 0; i < 100; i++)
            {
                tt.AddThreadAction(delegate
                                       {
                                           for (int j = 0; j < 10; j++)
                                           {
                                               c.Increment();
                                               Thread.Sleep(new Random(j+1).Next(100,300));
                                           }
                                       });
            }
          
            //this test will run for 22.5 seconds
            tt.RunBehavior=ThreadRunBehavior.RunForSpecificTime;
            tt.StartAllThreads(22500);
        }
 
```

#### **ThreadTester** works by getting a delegate from the developer which will be run in a separate thread. You can add as many separate delegates as you’d like. Each one will be run in a separate thread when you call ThreadTester.StartAllThreads().

**AddThreadAction:**

Takes a delegate with a void return value and no parameters. In the delegate you write code that would do something that a separate thread would do to your object (like call a method.

**RunBehavior:**

There are two run behaviors:

> **RunUntilAllThreadsFinish**: For each delegate passed in, a thread will be created that will execute that delegate exactly once. When all threads have finished or if a timeout occurs, the ThreadTester will stop blocking it’s “StartAllThreads()” method.
>
> This behavior is good if you'd like to test your object for a known amount of times.

> **RunForSpecificTime**: For each delegate passed in, a thread will be created that will execute that delegate exactly once. When that thread is finished, a **new thread** will be created which will execute that delegate again. This behavior will continue until the timeout specified in the **StartAllThreads**() method has been reached. Then ThreadTester will stop blocking.
>
> This behavior is good if you'd like to stress test your object for a known amount of elapsed time. Even if all threads finish, they will re-run until the time has elapsed.

## More in Agile

[All posts in Agile](https://osherove.com/blog/category/agile)

- Jun 25, 2007

    ### [ThreadTester with new Ability: StopWhenTrue() and thread polling](https://osherove.com/blog/2007/6/25/threadtester-with-new-ability-stopwhentrue-and-thread-pollin.html)

- Jun 24, 2007

    ### [Agile Israel Conference 2007 - Call For Speakers](https://osherove.com/blog/2007/6/24/agile-israel-conference-2007-call-for-speakers.html)

- Jun 21, 2007

    ### [Que Sera Sera - A song about Agile Development](https://osherove.com/blog/2007/6/21/que-sera-sera-a-song-about-agile-development.html)

- Jun 20, 2007

    ### [HTTPSimulator - Simulating HTTP Requests for unit testing made easier](https://osherove.com/blog/2007/6/20/httpsimulator-simulating-http-requests-for-unit-testing-made.html)


---

## About the author

**Roy Osherove**: Senior Solutions Architect at AWS working on AI for production and AI-driven development; author of The Art of Unit Testing and Elastic Leadership, with about 20 years of consulting and training on unit testing, TDD, team leadership and continuous delivery.

### Sites

- [RobotPaper](https://robotpaper.ai/): This blog: AI patterns and anti-patterns, AI and coding agents, and engineering leadership.
- [osherove.com](https://osherove.com): Roy's personal site. Author of The Art of Unit Testing and Elastic Leadership; consulting and training on unit testing, TDD, team leadership and continuous delivery, plus about 20 years of blog posts.
- [The Art of Unit Testing](https://www.artofunittesting.com): The Art of Unit Testing, 3rd Edition (Manning): readable, maintainable, trustworthy unit tests, plus TDD workshops in C#, JavaScript, Java and Kotlin.
- [5whys.com](https://www.5whys.com): Roy's writing on software team leadership: self-organizing teams, surviving chaos, learning mode and the Elastic Leadership model.
- [Pipeline Driven](https://pipelinedriven.org): Continuous delivery and DevOps practices: build patterns, pipeline-friendly testing, DevOps metrics and enterprise DevOps.
- [Elastic Leadership](https://www.elasticleadership.com): Elastic Leadership, Roy's framework for software team leaders (survival, learning and self-organizing modes).

### Social

- X: https://x.com/royosherove
- LinkedIn: https://www.linkedin.com/in/osherove/

### Contact

- Contact form: https://forms.gle/jQSx5KoXvrVA1JCK7

### License

Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page). License: https://creativecommons.org/licenses/by/4.0/
