The dependency injection also called as "context injection" , the specflow supports dependency framework able to instantiate and inject class instances for scenarios. We can share the state between step definitions in different Binding classes. We can use context Injection in Test automation to share the data and to share the driver object.
Conditions:
- The objects of context injection is limited to one scenario execution
- The constructor should be public and if there are multiple constructors then first one will be taken
- The injection is resolved recursively until they are all satisfied
- If the injected objects implement IDisposable then it will be disposed only after the scenario is executed.
How to use context injection:
Create the POCOs classes to represent the data and Define as constructor parameters in every binding class that requires them.
Save the constructor argument to instance fields and we use them in the step definitions.
Create the POCO Class with fields to share the context
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpecFlowProject1.Helper
{
public class CustomerInfo
{
public string username { get; set; }
public string lastname { get; set; }
public string postcode { get; set; }
}
}
Then define the Poco class in the constructor of every step definitions. Now the context can be shared between the steps in a scenario
using SpecFlowProject1.Helper;
using TechTalk.SpecFlow.Assist;
namespace SpecFlowProject1.StepDefinitions
{
[Binding]
public class AddCustomerStepDefinitions
{
private readonly CustomerInfo custInfo;
public AddCustomerStepDefinitions(CustomerInfo custInfo)
{
this.custInfo = custInfo;
}
[Given(@"user navigate the url in the browser")]
public void GivenUserNavigateTheUrlInTheBrowser()
{
Console.WriteLine("User navigate the URL");
custInfo.username = "Tom";
custInfo.lastname = "Jerry";
custInfo.postcode = "23232323";
}
[When(@"user select the manager login")]
public void WhenUserSelectTheManagerLogin()
{
Console.WriteLine("Manager Login...");
}
[When(@"add the customer with ""([^""]*)"", ""([^""]*)"", ""([^""]*)""")]
public void WhenAddTheCustomerWith(string usernam, string lastnam, string postcod)
{
//Console.WriteLine("Customer added with "+username);
Console.WriteLine(custInfo.username);
Console.WriteLine(custInfo.lastname);
Console.WriteLine(custInfo.postcode);
}
}
}
using SpecFlowProject1.Helper;
using System;
using TechTalk.SpecFlow;
namespace SpecFlowProject1.StepDefinitions
{
[Binding]
public class ManagerStepDefinition
{
private readonly CustomerInfo custInfo;
public ManagerStepDefinition(CustomerInfo custInfo)
{
this.custInfo = custInfo;
}
[Then(@"verify the manager role data")]
public void ThenVerifyTheManagerRoleData()
{
Console.WriteLine(custInfo.username);
Console.WriteLine(custInfo.lastname);
Console.WriteLine(custInfo.postcode);
}
}
}