Gáspár Nagy on software

coach, trainer and bdd addict, creator of SpecFlow

SpecFlow tips: When to clean the database

by Gáspár on February 23, 2015

We were always told to clean up after ourselves when we were children, this is also what I teach to my daughters. Probably due to this, when writing the first integration tests that inserts data to a database, devs cleanup (or reset) the database after the test has been executed (with an [AfterScenario] SpecFlow hook, for example). In reality, however, it is much more practical to do the cleanup before the scenario execution.

Why?

No manual cleanup. Integration can take longer to run and they might terminate in many different ways, e.g. the process is killed. There is no way to guarantee that the [AfterScenario] hook will be executed in every case. And should the process crash, the system collapses and you are super nervous, the least thing you want to deal with is to reset the database manually.

Predictable behavior. As a follow up of the previous point, it is much easier to keep a consistent and predictable behavior for your tests, if they consider the “clean database” as precondition.

Easier post-mortem investigation. Unfortunately tests might fail. And if they fail, you need to understand why. In this case, it can be very helpful to look at the current state of the database and see what is in.

So the conclusion is that the best option is if you reset the database to a clean state or to a known baseline before the scenario execution in a [BeforeScenario] hook. There are many different ways to reset the database (deserves an own post). The following example truncates a selected set of tables before every scenario.

Developing with SpecFlow Course in London, March 9th – 11th, 2015

Integration testing, Gherkin scenario writing and SpecFlow usage are the topics of my upcoming course in London, March 9th – 11th, 2015. If you would like to learn more about these topics. See course page for details. 10% discount is provided from the list price, if you mention code BLOG345.

Comments are closed.