Run code once before and after ALL tests in xUnit.net

后端 未结 8 867
野趣味
野趣味 2020-12-02 15:15

TL;DR - I\'m looking for xUnit\'s equivalent of MSTest\'s AssemblyInitialize (aka the ONE feature it has that I like).

Specifically I\'m looking for it

8条回答
  •  盖世英雄少女心
    2020-12-02 15:52

    Create a static field and implement a finalizer.

    You can use the fact that xUnit creates an AppDomain to run your test assembly and unloads it when it's finished. Unloading the app domain will cause the finalizer to run.

    I am using this method to start and stop IISExpress.

    public sealed class ExampleFixture
    {
        public static ExampleFixture Current = new ExampleFixture();
    
        private ExampleFixture()
        {
            // Run at start
        }
    
        ~ExampleFixture()
        {
            Dispose();
        }
    
        public void Dispose()
        {
            GC.SuppressFinalize(this);
    
            // Run at end
        }        
    }
    

    Edit: Access the fixture using ExampleFixture.Current in your tests.

提交回复
热议问题