Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for writing parallel unit tests

I'm looking into using parallel unit tests for our project(s) and was wondering about any best practices for actually writing such parallel unit tests.

like image 837
Brett Rigby Avatar asked Oct 27 '09 09:10

Brett Rigby


People also ask

Should unit tests be run in parallel?

Running unit tests in parallel can significantly improve the speed at which they run. However, you have to make sure that one test does not affect another in any way. Else your tests are green most of the time, but sometimes one or more tests will fail. Both tests depend on IRepository .


1 Answers

If by parallel unit tests you mean tests that can run concurrently, the most important advice I can give you is to avoid so-called Shared Fixtures.

The book xUnit Test Patterns describe the term Fixture, which basically can be described as the entire context in which each test case executes, including persistent and transient data.

A Shared Fixture indicates that test cases share some context while running. If that context is mutable, race conditions may occur.

Keeping a Shared Fixture immutable (a so-called Immutable Shared Fixture) will allow you to run tests in parallel, but even better, so-called Fresh Fixtures (where each test case has its own Fixture) are thread-safe by definition, since only the test case itself has access to the Fixture.

Examples of Shared Fixtures include any sort of test that use a shared database, but also include tests where you have static in-memory state in either the System Under Test (SUT) or the tests themselves, so you need to avoid that.

You should also keep in mind that if your SUT accesses shared (static) data, that access itself must be thread-safe.

like image 70
Mark Seemann Avatar answered Nov 16 '22 02:11

Mark Seemann