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

后端 未结 8 865
野趣味
野趣味 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:46

    You can use IUseFixture interface to make this happen. Also all of your test must inherit TestBase class. You can also use OneTimeFixture directly from your test.

    public class TestBase : IUseFixture>
    {
        protected ApplicationFixture Application;
    
        public void SetFixture(OneTimeFixture data)
        {
            this.Application = data.Fixture;
        }
    }
    
    public class ApplicationFixture : IDisposable
    {
        public ApplicationFixture()
        {
            // This code run only one time
        }
    
        public void Dispose()
        {
            // Here is run only one time too
        }
    }
    
    public class OneTimeFixture where TFixture : new()
    {
        // This value does not share between each generic type
        private static readonly TFixture sharedFixture;
    
        static OneTimeFixture()
        {
            // Constructor will call one time for each generic type
            sharedFixture = new TFixture();
            var disposable = sharedFixture as IDisposable;
            if (disposable != null)
            {
                AppDomain.CurrentDomain.DomainUnload += (sender, args) => disposable.Dispose();
            }
        }
    
        public OneTimeFixture()
        {
            this.Fixture = sharedFixture;
        }
    
        public TFixture Fixture { get; private set; }
    }
    

    EDIT: Fix the problem that new fixture create for each test class.

提交回复
热议问题