Generating Code Behind Files using MSBuild

2021-05-11 21-05-11
Using SpecFlow

Share!

 

Since SpecFlow 1.9, your can generate the code-behind files for feature files (*.feature.cs) at compile time. To do so, you need to use a MSBuild Task. The documentation is here.

Pros

  • Feature files and code-behind files are always in sync
  • No need to check the feature.cs files into your source control system
  • Works without Visual Studio
  • Works for both .NET Full Framework and .NET Core

Cons

  • When adding a new file, the CustomTool entered in the feature file’s properties currently has to be removed each time
  • Realtime test discovery will only find new tests after the project has been (re)built

Best practises

Store code-behind files in same folder as the feature file

In the past, we recommended moving the generated code-behind files to a different folder from your feature files.
We no longer recommend this approach, as you will otherwise experience problems with up-to-date checks in MSBuild.

Additionally, Microsoft has since fixed a bug in VS, meaning that navigating from the Test Explorer to the feature file works again (see here). For this to work, the code-behind files need to be located by VS, and having the generated files in a separate folder will break this feature again.

Known Bugs

  • Prior to SpecFlow 2.4.1, Visual Studio sometimes does not recognize that a feature file has changed. To generate the code-behind file, you therefore need to rebuild your project. We recommend using SpecFlow 2.4.1 or higher, where this is no longer an issue.

Enabling MSBuild Code Behind Generation

Classic Project System

  1. Add the NuGet package SpecFlow.Tools.MsBuild.Generation with the same version as SpecFlow to your project.
  2. Remove all SpecFlowSingleFileGenerator custom tool entries from your feature files.

 

SDK style project system

Please use at least SpecFlow 2.4.1, as this version fixes the above issue in 2.3.*.

  1. Add the NuGet package SpecFlow.Tools.MsBuild.Generation with the same version as SpecFlow to your project
  2. Remove all SpecFlowSingleFileGenerator custom tool entries from your feature files.

    Common issues

    After upgrading the NuGet packages, the code-behind files are not generated at compile time

    If you are using the classic project system, the previous MSBuild target may no longer located at the end of your project. NuGet ignores entries added manually, and places the MSBuild imports at the end.  However, the AfterUpdateFeatureFilesInProject target needs to be defined after the imports, because otherwise it will be overwritten with an empty definition. If this happens, your code-behind files are not compiled as part of the assembly.

    Linked files are not included

    If you link feature files into a project, no code-behind file is generated for them (see GitHub Issue 1295).

    More infos about MSBuild: