SpecFlowOSS / SpecFlow

#1 .NET BDD Framework. SpecFlow automates your testing & works with your existing code. Find Bugs before they happen. Behavior Driven Development helps developers, testers, and business representatives to get a better understanding of their collaboration
https://www.specflow.org/
Other
2.22k stars 752 forks source link

Fix #2600 by preserving ExecutionContext and reuse it for subsequent binding method invocations #2658

Closed gasparnagy closed 1 year ago

gasparnagy commented 1 year ago

This PR fixes #2600 by saving and reusing the ExecutionContext for the subsequent binding method invocations. ExecutionContext is pretty complex and hard to understand and also the behavior of AsyncLocal<T> is not straightforward to understand.

The bottom line is: AsyncLocal<T> now works as in SpecFlow v3 (and is it supposed to): you can change the value in ctor and sync step definitions, but the changes in async step definitions are discarded (this is how ExecutionContext works).

If you want to use AsyncLocal<T> and be able to change it in sync/async step definitions, you should use AsyncLocal<StrongBox<T>> and initialize it in ctor, like:

private readonly AsyncLocal<StrongBox<string>> _boxedAsyncLocal = new() { Value = new StrongBox<string>("ctor-value") };

A bit more tech detail (also included in BindingDelegateInvoker as comment):

To be able to simulate the behavior of sequential async or sync steps in a test, we need to ensure that the next step continues with the ExecutionContext that the previous step finished with.

Without preserving the ExecutionContext this would not happen because the async methods all the way up to the generated test method (for example this method) are discarding the ExecutionContext changes at the end, so the next step would start with an "empty" ExecutionContext again.

It is important that no methods from here (until the user's binding method) is marked with 'async' otherwise that would again discard the ExecutionContext.

The ExecutionContext only flows down, so async binding methods cannot directly change it, but even if all binding method is async the constructor of the binding classes are run in sync, so they should be able to change the ExecutionContext. (The binding classes are created as part of the 'bindingDelegate' this method receives.

Types of changes

Checklist:

This is to avoid a breaking change in v4, so no need to add an entry to chanelog.