Search code examples
c#unit-testingnunit

NUnit - prevent 2 specific classes from running in parallel


I have a test project with many tests and many test classes. Most of them can run in parallel without any problem, but there are 2 specific test classes whose tests access a certain file, and therefore cannot run in parallel.

I guess that if I put [Parallelizable(ParallelScope.All)] on all other classes and [Parallelizable(ParallelScope.None)] on these 2 classes, then it should be safe, but AFAIU it also means that these 2 classes won't run in parallel with any other class, which is not what I want, as it's not the most efficient solution.

Is there any other, more efficient way to achieve that?


Solution

  • Few points to consider:

    • [Parallelizable] or [NonParallelizable] may be specified on multiple levels of the tests, with lower-level specifications overriding higher ones to a certain degree.
    • It is important to note that a parallel or non-parallel specification only applies at that level where it appears and below. It cannot override the settings on higher-level tests.

    For your situation, you can create Parallel class with non-parallel methods: The methods within this class run sequentially, usually on the same thread that ran the class one-time setup, but may actually be running in parallel with other, unrelated methods from other classes. So your class can be:

    [Parallelizable(ParallelScope.All)]
    public class MyClass1 
    {
        [NonParallelizable]
        [Test]
        public void Test1()
        {
        }
    
        [NonParallelizable]
        [Test]
        public void Test2()
        {
        }
    }
    
    [Parallelizable(ParallelScope.All)]
    public class MyClass2 //Another class in same Assembly
    {
        //methods within this class will run in parallel with other 
        //class methods within same assembly except method Test1 and Test2 of MyClass1
    } 
    

    Hope this helps. Details here