SpecFlow: ClassInitialize and TestContext

robert.oh. picture robert.oh. · Aug 31, 2012 · Viewed 13.2k times · Source

first of all I'm new to SpecFlow.

I have a feature file which I have / want to automate using MSTest to run as a functional test involving a fully set up server, data access ... For this purpose I have to configure the server with the data in the SpecFlow's 'Given' blocks and start it afterwards. I also have to copy some files to the test's output directory.

In the non-SpecFlow functional tests I was using the ClassInitialize attribute to get the TestDeploymentDir from the TestContext; something like this:

[ClassInitialize]
public static void ClassSetup(TestContext context)
{
  TargetDataDeploymentRoot = context.TestDeploymentDir;
}

Now with SpecFlow I can't use this attribute anymore as it is used by SpecFlow itself. Some new attributes do exist, like BeforeFeature which acts similarly BUT it doesn't pass on the TestContext as a parameter.

I just need to get access to the TestContext's TestDeploymentDir in order to copy some files there before really lauching my functional test server - easily doable without SpecFlow but almost impossible with SpecFlow.

How to deal with this issue?

Is it possible at all?

Thanks a lot for advice!

robert


Environment:

  • Visual Studio 2012
  • SpecFlow 1.9.0.77

Answer

codevision picture codevision · Jun 3, 2013

In order to have access to values in the TestContext you have to create partial class for each scenario file you have in which you add the .

using Microsoft.VisualStudio.TestTools.UnitTesting;
using TechTalk.SpecFlow;

/// <summary>
/// Partial class for TestContext support.
/// </summary>
public partial class DistributionFeature
{
    /// <summary>
    /// Test execution context.
    /// </summary>
    private TestContext testContext;

    /// <summary>
    /// Gets or sets test execution context.
    /// </summary>
    public TestContext TestContext
    {
        get
        {
            return this.testContext;
        }

        set
        {
            this.testContext = value;

            //see https://github.com/techtalk/SpecFlow/issues/96
            this.TestInitialize();
            FeatureContext.Current["TestContext"] = value;
        }
    }
}

Then you could access the deployment directory from your steps using

var testContext = (TestContext)FeatureContext.Current["TestContext"];
var deploymentDir = testContext.TestDeploymentDir;

If you have too many scenarios, then you probably has to automate creation of such files with T4.