techtalk/SpecFlow — Issue #139: BeforeTestRun is run twice if an exception occurs the first time around
Author: rix0rrr
Created: 2011-10-25 09:26:32+00:00
State: open

**Summary**

If I have a hook marked `[BeforeTestRun]`, and exception occurs in this handler the first time it is executed (but not the next time), it will be called twice in succession on the next feature. And the `[AfterTestRun]` handler is *never* executed.

In our case, the setup has to do with resource acquisition and the call after the successful call will fail because the resource is already acquired.

**Minimal example**

```
namespace SpecFlowBug
{
[Binding]
public class Bindings
{
private static bool firstRunExplode = true;

[BeforeTestRun]
public static void BeforeTestRun()
{
Console.WriteLine("BeforeTestRun");
if (firstRunExplode)
{
firstRunExplode = false;
throw new InvalidOperationException("Boom");
}
}

[AfterTestRun]
public static void AfterTestRun()
{
Console.WriteLine("AfterTestRun");
}

[Then("Test")]
public void Live()
{
Console.WriteLine("Doing the test.");
}
}
}
```

If I now run two different features I get the following output:

```
BeforeTestRun
.FBeforeTestRun
BeforeTestRun
.Then Test
Doing the test.
-> done: Bindings.Live() (0,0s)

Tests run: 2, Errors: 0, Failures: 1, Inconclusive: 0, Time: 0,3620362 seconds
Not run: 0, Invalid: 0, Ignored: 0, Skipped: 0
```

As you can see:

First, BeforeTestRun is executed, and fails. Then, BeforeTestRun is executed *twice in succession*. Then the second test runs. Finally, AfterTestRun is *never* executed.