Await Tasks in Test Setup Code in xUnit.net?

前端 未结 2 1991
情歌与酒
情歌与酒 2020-12-30 20:02

The exact situation is I\'m doing E2E tests with Protractor.NET (.NET port of AngularJS\'s Protractor E2E framework) and I would like to make some web requests (and the API

相关标签:
2条回答
  • 2020-12-30 20:33

    I would use AsyncLazy

    http://blog.stephencleary.com/2012/08/asynchronous-lazy-initialization.html

    In my case I want to run some integration tests against a self hosted web api.

    public class BaseTest() 
    {
        private const string baseUrl = "http://mywebsite.web:9999";
    
        private static readonly AsyncLazy<HttpSelfHostServer> server = new AsyncLazy<HttpSelfHostServer>(async () =>
        {
            try
            {
                Log.Information("Starting web server");
    
                var config = new HttpSelfHostConfiguration(baseUrl);
    
                new Startup()
                    .Using(config)
                    .Add.AttributeRoutes()
                    .Add.DefaultRoutes()
                    .Remove.XmlFormatter()
                    .Serilog()
                    .Autofac()
                    .EnsureInitialized();
    
                var server = new HttpSelfHostServer(config);
                await server.OpenAsync();
    
                Log.Information("Web server started: {0}", baseUrl);
    
                return server;
            }
            catch (Exception e)
            {
                Log.Error(e, "Unable to start web server");
                throw;
            }
        });
    
        public BaseTest() 
        {
            server.Start()
        }
    }
    
    0 讨论(0)
  • 2020-12-30 20:35

    xUnit has an IAsyncLifetime interface for async setup/teardown. The methods you need to implement are Task InitializeAsync() and Task DisposeAsync().

    InitializeAsync is called immediately after the class has been created, before it is used.

    DisposeAsync is called just before IDisposable.Dispose if the class also implements IDisposable.

    e.g.

    public class MyTestFixture : IAsyncLifetime
    {
        private string someState;
    
        public async Task InitializeAsync()
        {
            await Task.Run(() => someState = "Hello");
        }
    
        public Task DisposeAsync()
        {
            return Task.CompletedTask;
        }
    
        [Fact]
        public void TestFoo()
        {
            Assert.Equal("Hello", someState);
        }
    }
    
    0 讨论(0)
提交回复
热议问题