[SOLVED] Execute unit tests serially (rather than in parallel)

Issue

This Content is from Stack Overflow. Question asked by Marlene

I have one test class that is unit-testing a class that is used as injection a lot of places in my project.

When I run everything parallell, I see that sometimes the initialized object in my one test class “fleets” over to the other tests and mess them up.

Is there a simple way for me to run this one test class alone, and then all the rest parallell afterwards? I have seen this solution (Execute unit tests serially (rather than in parallel)) but it does not solve my problem as my issue is about one test-class that can not run parallell towards anything, and then the rest can run optimally afterwards / before.

I don’t want to run everything sequential. They are all in the same test assembly.



Solution

Each test class is a unique test collection and tests under it will run in sequence, so if you put all of your tests in same collection then it will run sequentially.

In xUnit you can make following changes to achieve this:

Following will run in parallel:

namespace IntegrationTests
{
    public class Class1
    {
        [Fact]
        public void Test1()
        {
            Console.WriteLine("Test1 called");
        }

        [Fact]
        public void Test2()
        {
            Console.WriteLine("Test2 called");
        }
    }

    public class Class2
    {
        [Fact]
        public void Test3()
        {
            Console.WriteLine("Test3 called");
        }

        [Fact]
        public void Test4()
        {
            Console.WriteLine("Test4 called");
        }
    }
}

To make it sequential you just need to put both the test classes under same collection:

namespace IntegrationTests
{
    [Collection("Sequential")]
    public class Class1
    {
        [Fact]
        public void Test1()
        {
            Console.WriteLine("Test1 called");
        }

        [Fact]
        public void Test2()
        {
            Console.WriteLine("Test2 called");
        }
    }

    [Collection("Sequential")]
    public class Class2
    {
        [Fact]
        public void Test3()
        {
            Console.WriteLine("Test3 called");
        }

        [Fact]
        public void Test4()
        {
            Console.WriteLine("Test4 called");
        }
    }
}

For more info you can refer to this link


This Question was asked in StackOverflow by jrista and Answered by Abhinav Saxena It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?