Search code examples
c#visual-studiospecflowgherkinspecrun

Specflow - How to get Target Name from srprofile programatically in C#


Is there any way to get the Target name defined in specflow's srs profile ?

Below is what is defined in srs profile,

<Targets>
<Target name="Login">
      <Filter>@login</Filter>
</Target>
</Targets>

I want to get the name of the target "Login" and save it in a variable in C#.


Solution

  • We don't have an API to get the target name, but you can get to it with a little bit more stuff in the srProfile.

    This is how you do it:

    <?xml version="1.0" encoding="utf-8"?>
    <TestProfile xmlns="http://www.specflow.org/schemas/plus/TestProfile/1.5">
      <Targets>
        <Target name="Target1">
          <DeploymentTransformationSteps>
            <EnvironmentVariable variable="RUNNER_TARGET" value="Target1" />
          </DeploymentTransformationSteps>
        </Target>
        <Target name="Target2">
          <DeploymentTransformationSteps>
            <EnvironmentVariable variable="RUNNER_TARGET" value="Target2" />
          </DeploymentTransformationSteps>
        </Target>
      </Targets>
    </TestProfile>
    

    You specify a deployment transformation step which sets an environment variable to the name of the target.

    In your bindings, you can get the value of the environment variable by normal .NET APIs.

    var targetName = Environment.GetEnvironmentVariable("RUNNER_TARGET");
    

    You can find a complete example here: https://github.com/SpecFlowOSS/SpecFlow.Plus.Examples/tree/master/AccessTargetName


    Full disclosure: I am one of the developers of SpecFlow and SpecFlow+