Advanced SpecFlow: Using Hooks to Run Additional Automation Code

SpecFlow is a tool that allows the writing of business-readable tests that can then be automated in code. If you’re new to SpecFlow check out my Pluralsight course to get up to speed before looking at these more advanced topics.

In addition to executing test automation code in step definitions, SpecFlow provides a number of additional “hooks” to allow additional code execution at various points during the test execution lifecycle.

For this example, consider the following feature:

Feature: SomeFeature

Scenario: Add New Contact Name
    Given I have entered Sarah
    When I choose add
    Then the contact list should show the new contact

With the following step definitions:

using TechTalk.SpecFlow;

namespace SpecFlowHooks
{
    [Binding]
    public class SomeFeatureSteps
    {
        [Given]
        public void Given_I_have_entered_NEWNAME(string newName)
        {
            // etc.
        }
        
        [When]
        public void When_I_choose_add()
        {
            // etc.   
        }
        
        [Then]
        public void Then_the_contact_list_should_show_the_new_contact()
        {
            // etc.
        }
    }
}

When the scenario is executed we get the following test output:

More...

SHARE:

Advanced SpecFlow: Sharing Data Between Steps with Context Injection

SpecFlow is a tool that allows the writing of business-readable tests that can then be automated in code. If you’re new to SpecFlow check out my Pluralsight course to get up to speed before looking at these more advanced topics.

Individual step definitions that represent the natural language scenarios are separate methods that get executed. Often we need to pass data between these steps. The simplest approaches to get started with are to use simple fields in the class containing the steps or to use the Scenario Context. An alternative to these approaches is to use Context Injection.

For example, imagine the following scenario:

Feature: SomeFeature

Scenario: Add New Contact Name
    Given I have entered Sarah
    When I choose add
    Then the contact list should show the new contact

More...

SHARE: