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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With