Search code examples
c#async-awaitnunitbddspecflow

Specflow steps with await for async API


We're trying to get the following scenrio step to break the test in case failure happens within DoAyncStuff() method:

[Given(@"There is something")]
public async Task GivenSomething()
{
    await DoStuff();
}

private async Task DoStuff()
{
    await Task.Run(() => Thread.Sleep(1000));
    throw new ApplicationException("Boom");
}

But it actually makes a happy green-run until you use .Wait() or .Result:

[Given(@"There is something")]
public void GivenSomething()
{
    DoStuff().Wait();
}

The problem seems to be in the NUnit generated-spec which looks like this:

public virtual void SomethingAsync()
{
    ...
    testRunner.Given("There is something", ...);
    ...
}

which seems to work with the following code:

public virtual async Task SomethingAsync()
{
    ...
    await this.ScenarioSetup(scenarioInfo);
    ...
}

The code above is manually edited auto-generated file, so I'm actually looking for a way to produce following code automatically.

The documentation seems to be the only option available for asyncronous API but it's actually for Silverlight and as far as I understand uses some kind of API, while we'd preffer to use native C# await keyword.

Is there a way to handle natively async/await is SpecFlow steps?


Solution

  • In the current released version (2.1) version there is no support for async and await, support was added (via this merged PR) in v2.2 which is available from the CI server, but there is not an official release yet.

    [EDIT]

    2.2 has been released and supports async await in tests.