Lean BDD with even more Code Generation

Plainionist
2 min readMar 7, 2023

--

Just recently, I wrote about my BDD approach in one of my projects in this article. I have used this setup now for a while and it actually worked quite well for me but there is one thing which turned out to be quite annoying over time.

The problem was: the Test Explorer couldn’t identify the sources of a test case which means, if the test case failed, I couldn’t simply double click the sources to navigate to the test case and also starting the test case with debugger attached was not easily possible.

The reason of this problem was that the test cases were generated at runtime using reflection and NUnits TestCaseSource mechanism which means there are simply no sources for these test cases.

The only solution to this problem I saw was generating the test cases as source code at build time.

For that, I first created a parser which reads the feature title as well as the scenario titles from the feature files of a given project.

Then I had to update the existing code generator to also generate test cases (methods) for each scenario. Earlier I used a template engine to generate the code but the engine I have chosen turned out to be too limited for the new needs so I removed it again and now generate the code using strings and a TextWriter.

For now this is a feasible approach as most of the actual logic, needed to find and execute a particular scenario using TickSpec, is still in a base class similar to the one shown above.

Finally, I even added #line directives pointing to the feature file instead of the generated "code behind" which causes VS Test Explorer to navigate the particular scenario in the feature file when double clicking the test case.

The “upgraded” approach is available as individual GitHub project as well as NuGet package.

Give it a try in your next F# and BDD project and let me know how it works for you.

Originally published at http://www.plainionist.net on March 7, 2023.

--

--