14

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?

2ooom
  • 1,760
  • 1
  • 23
  • 37

1 Answers1

13

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.

Sam Holder
  • 32,535
  • 13
  • 101
  • 181
  • Is there any update on this?, I installed the 2017 version of specflow and it doesn't seem to generate async tests, But the version of the specflow nuget is 2.2. From the generated code it says the generator is 2.0 – Keith Nicholas Apr 04 '17 at 02:59
  • 1
    Have the same problem in VS2017 and SpecFlow 2.2.0 with xUnit 2.2.0. Async Tests(the part I write, not the autogenerated code) are not awaited and the flow immediately goes to next steps. – Skorunka František Jul 26 '17 at 12:30
  • 1
    I'm running SpecFlow 2.2.0 and SpecFlow.xUnit 2.2.0 in VS 2017 and it works as expected. Maybe post as a question @SkorunkaFrantišek :-) – bytedev Oct 25 '17 at 10:41
  • I am using VS 2015 with SpecFlow 2.2.1 and when I decorate a step with async and use await inside, it goes to the next step. So for now I am using .Result in my async call. – Varga Tamas Dec 08 '17 at 11:14
  • 2
    @VargaTamas did you ensure your step uses `async Task` signature? I'm pretty sure it works. – Sam Holder Dec 11 '17 at 11:10
  • That was exactly the problem - the signature has to be async Task and then it works, I just forgot to update, thanks for the hint. – Varga Tamas Jan 29 '18 at 08:41