Search code examples
c#testingbddspecflowgherkin

How to set up individual tracing / logging with SpecFlow


For my SpecFlow tests, I want to setup an individual logging / tracing of the test progress during the execution of tests. E.g. i want to write

  • all passed / failed steps
  • started / ended scenarios
  • started / ended features

to the windows event log (in order to synchronize it with event log messages generated by other system components during the test).

I tried to use the [BeforeFeature], [BeforeScenario], [BeforeStep] Hooks for doing that, but it turned out that I do not have all the required information within this hooks. E.g. i do not know how to get the current text line of the current step executed (including line information, etc.) or the result (failed / passed) of the current step.

Is there a way to get this information within those hooks or in any other way during the execution of the test?

If not: Is there a way to customize the trace output created by Specflow in any other way?


Solution

  • In order to provide a custom implementation of ITestTracer you should create a plugin for SpecFlow.

    Create a class library project with a name CustomTracer.SpecflowPlugin. CustomTracer is your name of choice for plugin.

    Then put the following code into your new assembly

    [assembly: RuntimePlugin(typeof(CustomTracer.SpecflowPlugin.CustomTracerPlugin))]
    
    namespace CustomTracer.SpecflowPlugin
    {
        public class CustomTracerPlugin : IRuntimePlugin
        {
            public void RegisterDependencies(ObjectContainer container)
            {
    
            }
    
            public void RegisterCustomizations(ObjectContainer container, RuntimeConfiguration runtimeConfiguration)
            {
                container.RegisterTypeAs<CustomTracer, ITestTracer>();
            }
    
            public void RegisterConfigurationDefaults(RuntimeConfiguration runtimeConfiguration)
            {
    
            }
        }
    
        public class CustomTracer : ITestTracer
        {
            // Your implementation here
        }
    }
    

    Compile assembly and put in the project folder where your specs are (where .csprog file is).

    Edit app.config, specFlow section to include:

    <plugins>
      <add name="CustomTracer" path="." type="Runtime"/>
    </plugins>
    

    That is it. Your plugin should load and your custom ITracer implementation should be called during scenario execution. You can even debug it, if you run scenarios under debug.