Waiting for tasks in test installation code at xUnit.net?

The exact situation is that I am running E2E tests using Protractor.NET (the .NET port for the AngularJS Protractor E2E platform) and I would like to make some web requests (and the API - System.Net.Http.HttpClient - has everything Async / Task ). In order to execute my test before I activate / validate, I need to complete this procedure for several tests.

I use xUnit.net as my test runner, which uses the interface ( IUseFixture<T> ) for the setup code for each fixture. It would be nice if there was an IAsyncUseFixture<T> that had a Task SetFixtureAsync(T t); or something like that. I do not think such a thing exists. Also, I don't think that constructors can use await , and constructors are the only way to execute the same block for every test in xUnit.net.

What are my options? .Result ? Isn't that a bad practice (dead end)?

+8
c # async-await
source share
3 answers

I just went with .Result . So far so good.

+2
source share

xUnit has an IAsyncLifetime interface for asynchronous install / stall. The methods required for implementation are Task InitializeAsync() and Task DisposeAsync() .

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

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

eg.

 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); } } 
+12
source share

I would use AsyncLazy

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

In my case, I want to run some integration tests using my own api web application.

 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() } } 
+1
source share

All Articles