Anyway to force NUnitlite run in the main thread?

Viewed 19

In NUnit/Nunitlite 3.13 ( or any other version of NUnit), is it possible to force the tests to run in main thread?

I've already decorated my test as Apartment(ApartmentState.STA), and yet, it still runs in a separate thread, as shown below:

enter image description here

Here's my code:

[TestFixture, Apartment(ApartmentState.STA)]
public class MetaClass
{
    [Test]
    public void RunA()
    {
        Assert.AreEqual(1,1);
    }
}

[Apartment(ApartmentState.STA)]
internal class Program
{
    static void Main(string[] args)
    {
        string directoryPlugin = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        string directoryReportUnit = Path.Combine(directoryPlugin, @"ReportUnit");
        Directory.CreateDirectory(directoryReportUnit);
        string fileInputXML = Path.Combine(directoryReportUnit, @"Report-NUnit.xml");


        string[] nunitArgs = new List<string>
        {
         
            "--trace=verbose" // Tell me everything
            ,"--result=" + fileInputXML
              ,"--workers=-1" //with or without this parameter, a parallel worker thread is still used 
        
        }.ToArray();


        new AutoRun().Execute(nunitArgs);
    }
}

Note that with or without the parameter "--workers=-1", a parallel worker thread is still used.

1 Answers

NUnit's ApartmentAttribute, used with ApartmentState.STA as you are doing, forces threads to run in the single threaded apartment. In addition, it has the side effect that the NUnit dispatcher will only run one one such test at a time... i.e. it uses the Non-Parallel test worker thread. However, it has nothing to do with what thread runs in the STA. So don't use that attribute expecting to influence the use of threads.

How the framework uses threads is controlled by the --workers option on the command-line. I'm not 100% sure, because this varies according to the version of the framework you are using, but I believe that --workers=-1 will get you closer to what you want because it eliminates use of the parallel dispatcher entirely.

Related