How to teach SpecFlow to add additional NUnit attr

2019-03-27 18:05发布

问题:

SpecFlow is great - and it helps us very much to do proper integration testing.

One thing I was wondering is whether there's a way to tell SpecFlow to add additional NUnit attributes to the test class it creates in the feature code-behind file.

Right now, my test class gets generated something like this:

[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.8.1.0")]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[NUnit.Framework.TestFixtureAttribute()]
[NUnit.Framework.DescriptionAttribute("Some action description here")]
public partial class MySampleFeature
{  
   ......
}

Is there any way in SpecFlow to tell it to add an additional NUnit attribute to define the category of the test - like this:

[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.8.1.0")]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[NUnit.Framework.TestFixtureAttribute()]
[NUnit.Framework.DescriptionAttribute("Some action description here")]
[NUnit.Framework.Category("LongRunningTests")]   <== add this "Category" attribute
public partial class MySampleFeature
{  
   ......
}

Adding this manually to the generated code-behind is wasteful - next time SpecFlow re-generates that code-behind, I have to remember doing it again (and chances are, I'll forget).

And if that capability is not yet present in SpecFlow - how to petition for this to be added? :-)

回答1:

In fact the NUnit.Framework.Category attribute is already supported if you use tags (look for the tags section) on your feature or scenarios. So if you write

@LongRunningTests
Feature: MySampleFeature

it will generate the proper Category attribute.

However if you want to have additional custom attributes you need to write a custom generator provider with implementing the IUnitTestGeneratorProvider interface and register with the unitTestProvider's generatorProvider attribute in your config's specflow section.

You can find the source of the built in implementations at github.



回答2:

To add to @nemesv's good answer, once you've added:

@LongRunningTests Feature: MySampleFeature

To execute from the console, do this:

nunit3-console.exe myTests.dll --where "cat==LongRunningTests"